Created
January 20, 2020 13:38
-
-
Save enif-lee/d271005653cbc1ac1e27e77081f521be to your computer and use it in GitHub Desktop.
ASP.NET Core DbContext Health Check
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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