Search code examples
c#health-check.net-7.0worker-service

How to configure HealthCheck with IHost?


In our current implementation of healthcheck's in worker service we do like this (simplified)

var options = new WebApplicationOptions {
    Args = args, 
    ContentRootPath = WindowsServiceHelpers.IsWindowsService() 
        ? AppContext.BaseDirectory 
        : default
};

var builder = WebApplication.CreateBuilder(options);

builder.Host.UseWindowsService();

builder.Services.AddHealthChecks().AddCheck<ServiceIsOnlineCheck>(nameof(ServiceIsOnlineCheck));
builder.Services.AddHostedService<Worker>();

var healthcheckoptions = new HealthCheckOptions
{
    ResponseWriter = ResponseWriters.WriteDetailedStatus,
    ResultStatusCodes =
            {
                [HealthStatus.Healthy] = StatusCodes.Status200OK,
                [HealthStatus.Degraded] = StatusCodes.Status200OK,
                [HealthStatus.Unhealthy] = StatusCodes.Status200OK
            }
};

var app = builder.Build();
app.UseHealthChecks("/health", healthcheckoptions);

app.Run();

When I create a new worker service in .NET 7, the setup in program.cs is completely different and I can not understand how we can set up health checks in them.

How do you implement it when program.cs looks like this? (we need to set our own response writer and other custom options)

IHost host = Host.CreateDefaultBuilder(args)
    .UseWindowsService(options =>
    {
        options.ServiceName = "Service Name";
    })
    .ConfigureWebHost(host =>
    {
        // ???
    })
    .ConfigureServices(services =>
    {
        services.AddHostedService<RunOnScheduleWorker>();
    })
    .Build();

host.Run();

Solution

  • This template uses the generic hosting (which was used in pre .NET 6 templates), so you can setup it with Startup. Here is a small working snippet which you can draw inspiration from:

    IHost host = Host.CreateDefaultBuilder(args)
        .UseConsoleLifetime()
        .ConfigureWebHostDefaults(builder =>
        {
            builder.UseStartup<Startup>();
        })
        .ConfigureServices(services => { services.AddHostedService<Worker>(); })
        .Build();
    
    
    host.Run();
    
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddHealthChecks();
        }
    
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseHealthChecks("/health");
        }
    }
    

    But you are not limited to using it, you can:

    • Switch to the one previously used, just copy-paste everything from the one you used.
    • Since you want to expose ASP.NET Core endpoint(s) - use corresponding project type and add just hosted service to it.

    Read more: