Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 979
lmcarreiro Avatar asked Aug 26 '18 15:08

lmcarreiro


People also ask

How would you add a health check on an ASP.NET Core API project you are working on?

Register health check services with AddHealthChecks in Startup. ConfigureServices . Create a health check endpoint by calling MapHealthChecks in Startup. Configure .

How can we inject the service dependency into the controller?

The first way of doing this is to inject a service into a controller. With an ASP. NET Core MVC application, we can use a parameter in the controller's constructor. We can add the service type and it will automatically resolve it to the instance from the DI Container.

How many types of dependency injection are there in ASP.NET Core?

NET Core provides three kinds of dependency injection, based in your lifetimes: Transient: services that will be created each time they are requested. Scoped: services that will be created once per client request (connection) Singleton: services that will be created only at the first time they are requested.


Video Answer


1 Answers

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.

like image 169
Yennefer Avatar answered Oct 08 '22 08:10

Yennefer