Reputation: 1107
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();
Upvotes: 3
Views: 1403
Reputation: 142018
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:
Read more:
Upvotes: 4