Search code examples
asp.net-corehealth-checkgrpc-dotnet

Trigger HealthCheck by code in aspnet core


I am working with microservice (multiple services) and want to have HealthCheck service which I can call and get health of all the running service. I wan't to trigger healthcheck for each of the service. The idea is to get health of each service via GRPC.

One of my service has :

''' services.AddHealthChecks() .AddCheck("Ping", () => HealthCheckResult.Healthy("Ping is OK!"), tags: new[] { "ping_tag" }).AddDbContextCheck(name: "My DB"); '''

How can I run health check through code when my GRPC endpoint is called in this service and get result.


Solution

  • When services.AddHealthChecks() is invoked, an instance of Microsoft.Extensions.Diagnostics.HealthChecks.HealthCheckService is added to the container. You can access this instance using dependency injection and call CheckHealthAsync to generate a health report which will use the registered health checks.

    In my project I needed to execute the health check, when a MassTransit event is received:

    public class HealthCheckQueryEventConsumer : IConsumer<IHealthCheckQueryEvent>
    {
        private readonly HealthCheckService myHealthCheckService;   
        public HealthCheckQueryEventConsumer(HealthCheckService healthCheckService)
        {
            myHealthCheckService = healthCheckService;
        }
    
        public async Task Consume(ConsumeContext<IHealthCheckQueryEvent> context)
        {
            HealthReport report = await myHealthCheckService.CheckHealthAsync();
            string response = JsonSerializer.Serialize(report);
            // Send response
        }
    }