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?
Register health check services with AddHealthChecks in Startup. ConfigureServices . Create a health check endpoint by calling MapHealthChecks in Startup. Configure .
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With