I created a custom Health Check that calls an injected service, and that service uses a DbContext to query the DB to get some info. When I launched my application I get the following error:
An attempt was made to use the context while it is being configured. A DbContext instance cannot be used inside OnConfiguring since it is still being configured at this point. This can happen if a second operation is started on this context before a previous operation completed. Any instance members are not guaranteed to be thread safe.
Is there a way to delay the health check until the DbContext is registered somewhere in the startup?
Below is my health check implementation.
public class HealthCheck : IHealthCheck
{
public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default(CancellationToken))
{
int userCount = dbService.GetUserCount(); // fails in the dbService here
if (userCount > 0)
return Task.FromResult(HealthCheckResult.Healthy("A healthy result."));
return Task.FromResult(new HealthCheckResult(context.Registration.FailureStatus, "An unhealthy result."));
}
}
This is how it is registered in the startup after my dbcontext is registered via AddDbContext
services.AddHealthChecks().AddCheck<HealthCheck>("user_health_check");