dotnet-architecture / HealthChecks

Experimental Health Checks for building services, such as with ASP.NET Core
Other
453 stars 124 forks source link

How to inject dependencies inside a custom checker? #90

Closed lmcarreiro closed 6 years ago

lmcarreiro commented 6 years ago

In the example:

public void ConfigureServices(IServiceCollection services)
{
    //...
    services
        .AddHealthChecks()
        .AddCheck(new SqlConnectionHealthCheck("MyDatabase", Configuration["ConnectionStrings:DefaultConnection"]));
    //...
}

public void Configure(IApplicationBuilder app)
{
    app.UseHealthChecks("/healthz");
}

I could add custom checks that implement the Microsoft.Extensions.Diagnostics.HealthChecks.IHealthCheck interface. But since I need to provide to the AddCheck method an instance instead of a type, and it needs to run inside the ConfigureServices method, I can't inject any dependency in my custom checker.

Is there any way to workaround this?

davidfowl commented 6 years ago

cc @rynowak

jasonwadsworth commented 6 years ago

The best work around I’ve come up with so far is to have a constructor that takes an IServiceCollection and pass the services object into your class. From there you can build an IServiceProvider and you can get your services from there. The downside to this is that you need to be sure all your DI dependencies are added before you do this.

JuergenGutsch commented 6 years ago

The interface of AddCheck isn't the best one. and could be more generic in the future:

services.AddCheck<SqlConnectionHealthCheck, SqlConnectionHealthCheckOptions>()
services.AddCheck<SqlConnectionHealthCheck, SqlConnectionHealthCheckOptions>(new SqlConnectionHealthCheckOptions())
services.AddCheck<SqlConnectionHealthCheck, SqlConnectionHealthCheckOptions>(options => {})
lmcarreiro commented 6 years ago

My question was answered here: https://stackoverflow.com/a/52029647/4871582

But I agree with @JuergenGutsch, the interface of AddCheck could be better.

lmcarreiro commented 6 years ago

We're making changes in preview2 that allow you to register health checks with any DI lifetime. You'll also be able to register health checks like builder.AddHealthCheck<T>

Closing this issue based on this comment from @rynowak in https://github.com/aspnet/Diagnostics/issues/464#issuecomment-416729281