The question is just as asked on the title. It is simple to perform a check for the database operations, queries, commands and event store but I am clueless as to how/what is the best way to perform a health check on a hostedservice. Could anyone advice?
Additionally from Simon B, this official Microsoft documentation has drafted out a complete guide to writing a health check structure for your Hosted services.
You need 3 elements:
The IHostedService
interface (and BackgroundService
base implementation) has overridable methods StartAsync()
and StopAsync()
. In our background service we have:
public override Task StopAsync(CancellationToken cancellationToken)
{
_logger.LogWarning("Background service stopping");
return Task.CompletedTask;
}
You could use this to run whatever you want to notify in some way when your HostedService
starts or stops.
If you need to have a way of polling the service, you could perhaps inject a singleton that has a simple status within it, that is set by these methods. Then, a health check controller on your API / website could also have that injected and read the status of the singleton. Something like this:
public interface IHostedServiceStatus
{
bool IsHostedServiceRunning { get; set; }
}
public class HostedServiceStatus : IHostedServiceStatus
{
public bool IsHostedServiceRunning { get; set; }
}
Set that up as a singleton, inject into your HostedService
and set IsHostedServiceRunning
on the StartAsync()
and StopAsync()
methods appropriately. Then also inject into your health check controller and read IsHostedServiceRunning
.