How do health checks interact with dependency injection scoping, particularly for checks that need a scoped service like a DbContext?
Short answer
Since health checks execute outside the normal per-request DI scope (they run on-demand when the health endpoint is hit, or via a background polling service), the health check middleware itself creates an appropriate DI scope when invoking each IHealthCheck implementation, so a…
Advertisement
AModel answer
Since health checks execute outside the normal per-request DI scope (they run on-demand when the health endpoint is hit, or via a background polling service), the health check middleware itself creates an appropriate DI scope when invoking each IHealthCheck implementation, so a health check class can safely take a constructor-injected scoped service like a DbContext just like it would in a controller -- but you should avoid manually caching or holding onto scoped services in a health check registered with a longer lifetime, since that could lead to using a disposed instance.
public class OrderDbHealthCheck(OrderDbContext db) : IHealthCheck { // scoped DbContext injected safely
public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken ct = default) {
return await db.Database.CanConnectAsync(ct) ? HealthCheckResult.Healthy() : HealthCheckResult.Unhealthy();
}
}
// Registration -- the health check itself is registered, DI scope handled automatically per invocation
builder.Services.AddHealthChecks().AddCheck<OrderDbHealthCheck>("orders-db");Real-world example
A health check class safely takes a constructor-injected scoped DbContext, relying on the health check middleware's automatic per-invocation DI scope creation, rather than needing to manually manage IServiceScopeFactory and scope lifetime themselves.
Likely follow-ups
- What would go wrong if a health check were mistakenly registered as a singleton but tried to cache a scoped dependency across invocations?
- How does this scoping behavior differ for a health check invoked from a background polling HostedService versus an HTTP request?
Related topics