Skip to content

Instantly share code, notes, and snippets.

@enif-lee
Created January 20, 2020 13:38
Show Gist options
  • Save enif-lee/d271005653cbc1ac1e27e77081f521be to your computer and use it in GitHub Desktop.
Save enif-lee/d271005653cbc1ac1e27e77081f521be to your computer and use it in GitHub Desktop.
ASP.NET Core DbContext Health Check
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Microsoft.Extensions.Logging;
namespace Common.Api.HealthCheck
{
public class DatabaseHealthCheck<TDbContext> : IHealthCheck where TDbContext : DbContext
{
private readonly ILogger _logger;
private readonly TDbContext _context;
public DatabaseHealthCheck(TDbContext context, ILogger<DatabaseHealthCheck<TDbContext>> logger)
{
_context = context;
_logger = logger;
}
public async Task<HealthCheckResult> CheckHealthAsync(
HealthCheckContext context,
CancellationToken cancellationToken = new CancellationToken())
{
var database = _context.Database;
await database.ExecuteSqlInterpolatedAsync($"select 1", cancellationToken);
if (await database.CanConnectAsync(cancellationToken))
return HealthCheckResult.Healthy("Database is operating normally.");
return HealthCheckResult.Unhealthy("Cannot connect to database");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment