Search code examples
c#asp.net-coreasp.net-core-webapi.net-6.0health-check

Adding multiple Healthchecks in .net 6 with custom IHealthCheck object


For my new requirement, I will have list of URLs(from configuration) and the number of URLs might be more then 10.I need to add IHealthCheck instances for each URL to have health status of all the URLs. Single URL I can add like below, But how to have Healthcheck for all the URLs

builder.Services.AddHealthChecks().AddCheck<UnknownURIHealthCheck>("ExternalHealthCheck");

IHealthCheck implementation is like

public class UnknownURIHealthCheck : IHealthCheck
{
    private readonly int _uri;
    public UnknownURIHealthCheck(int uri)
    {
        _uri = uri;
    }
    public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
    {
        if (_uri < 10)
            return Task.FromResult(HealthCheckResult.Healthy($"URI Value {_uri}"));
        else
            return Task.FromResult(HealthCheckResult.Unhealthy($"URI Value {_uri}"));
}

How to create IHealthCheck instance for each URI? Am I trying/looking in a wrong way for my requirement. Can some one help me?

Note: Declared _uri as integer for the purpose of explaining, _uri<10 will be replaced with actual uri's availability logic.


Solution

  • Instead of using the generic version of AddCheck, you can use an overload that takes an instance of the health check as a parameter:

    builder.Services
      .AddHealthChecks()
      .AddCheck(
        "ExternalHealthCheck-1",
        new UnknownURIHealthCheck("URL1"))
      .AddCheck(
        "ExternalHealthCheck-2",
        new UnknownURIHealthCheck("URL2"));
    

    If you want to add many health checks in a loop, you can use this approach:

    var urls = new string[] { "URL1", "URL2" };
    var bldr = builder.Services
      .AddHealthChecks();
    foreach (var url in urls)
    {
      bldr = bldr.AddCheck(
        "ExternalHealthCheck-" + url,
        new UnknownURIHealthCheck(url));
    }