Search code examples
c#asp.net-coredependency-injection.net-corehealth-monitoring

How to inject dependencies inside an ASP.NET Core Health Check


I'm trying to use the new ASP.NET Code 2.2 Healthchecks feature.

In this link on the .net blog, it shows an example:

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

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

I can 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?


Solution

  • As of .NET Core 3.0, the registration is simpler and boils down to this

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddHealthChecks();
        services.AddSingleton<SomeDependency>();
        services.AddCheck<SomeHealthCheck>("mycheck");
    }
    

    Note that you no longer have the singleton vs transient conflict as you use what the engine needs to use.

    The name of the check is mandatory, therefore you have to pick up one.

    While the accepted asnwer seems no longer to work.