36 lines
1.0 KiB
C#
36 lines
1.0 KiB
C#
using Microsoft.Extensions.Diagnostics.HealthChecks;
|
|
using NexusReader.Data.Persistence;
|
|
using System;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace NexusReader.Web.Services;
|
|
|
|
public class DatabaseHealthCheck : IHealthCheck
|
|
{
|
|
private readonly AppDbContext _dbContext;
|
|
|
|
public DatabaseHealthCheck(AppDbContext dbContext)
|
|
{
|
|
_dbContext = dbContext;
|
|
}
|
|
|
|
public async Task<HealthCheckResult> CheckHealthAsync(
|
|
HealthCheckContext context, CancellationToken cancellationToken = default)
|
|
{
|
|
try
|
|
{
|
|
var canConnect = await _dbContext.Database.CanConnectAsync(cancellationToken);
|
|
if (canConnect)
|
|
{
|
|
return HealthCheckResult.Healthy("Database is accessible.");
|
|
}
|
|
return HealthCheckResult.Unhealthy("Cannot connect to the database.");
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
return HealthCheckResult.Unhealthy("Database health check failed with exception.", ex);
|
|
}
|
|
}
|
|
}
|