How do I implement .NET Core Health Checks on a Hosted Service?

2/28/2020

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?

-- Nicholas
.net-core
kubernetes-health-check

2 Answers

4/1/2020

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:

  1. The HealthCheck class for your hosted service
  2. The HealthCheck Provider DI, along with the HealthCheck class' DI.
  3. A HealthCheck publisher
-- Nicholas
Source: StackOverflow

3/3/2020

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.

-- Simon B
Source: StackOverflow