Open
Description
Background and Motivation
I frequently find myself needing to use the Microsoft.Extensions.DependencyInjection.IHealthChecksBuilder.Add(HealthCheckRegistration registration)
extension method to register health checks that require use of the IServiceProvider
to setup the Health check dependencies. It would be nice to have an API for this scenario for registering health checks in consistency with the other extension methods, such as:
public static IHealthChecksBuilder AddCheck<T>(
this IHealthChecksBuilder builder,
string name,
HealthStatus? failureStatus,
IEnumerable<string> tags) where T : class, IHealthCheck
etc...
Proposed API
The API I would like to propose is as follows:
namespace Microsoft.Extensions.DependencyInjection;
public static class HealthChecksBuilderAddCheckExtensions
{
// existing code omitted for brevity
public static IHealthChecksBuilder AddCheck<T>(
this IHealthChecksBuilder builder,
string name,
Func<IServiceProvider, IHealthCheck> factory,
HealthStatus? failureStatus = null,
IEnumerable<string>? tags = null) where T : class, IHealthCheck
{
return builder.Add(new HealthCheckRegistration(name, factory, failureStatus, tags));
}
}
Usage Examples
The usage of this API would simplify registering of a health check that requires the use of the IServiceProvider
:
services.AddHealthChecks()
.AddCheck("DbConnectionCheck", sp =>
{
var configuration = sp.GetRequiredService<IConfiguration>();
var connectionString = configuration.GetConnectionString("DefaultConnectionString");
var provider = configuration.GetValue<string>("Configuration:DbProvider");
return new DbConnectionCheck(connectionString, dbProvider);
}, HealthStatus.Unhealthy, new[] { "dependency", "db-dependency" });
Alternative Designs
None
Risks
No known risks.