DbContextFactoryHealthCheck.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. using System;
  2. using System.Threading;
  3. using System.Threading.Tasks;
  4. using Microsoft.EntityFrameworkCore;
  5. using Microsoft.Extensions.Diagnostics.HealthChecks;
  6. namespace Jellyfin.Server.HealthChecks;
  7. /// <summary>
  8. /// Implementation of the <see cref="DbContextHealthCheck{TContext}"/> for a <see cref="IDbContextFactory{TContext}"/>.
  9. /// </summary>
  10. /// <typeparam name="TContext">The type of database context.</typeparam>
  11. public class DbContextFactoryHealthCheck<TContext> : IHealthCheck
  12. where TContext : DbContext
  13. {
  14. private readonly IDbContextFactory<TContext> _dbContextFactory;
  15. /// <summary>
  16. /// Initializes a new instance of the <see cref="DbContextFactoryHealthCheck{TContext}"/> class.
  17. /// </summary>
  18. /// <param name="contextFactory">Instance of the <see cref="IDbContextFactory{TContext}"/> interface.</param>
  19. public DbContextFactoryHealthCheck(IDbContextFactory<TContext> contextFactory)
  20. {
  21. _dbContextFactory = contextFactory;
  22. }
  23. /// <inheritdoc />
  24. public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
  25. {
  26. ArgumentNullException.ThrowIfNull(context);
  27. var dbContext = await _dbContextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
  28. await using (dbContext.ConfigureAwait(false))
  29. {
  30. if (await dbContext.Database.CanConnectAsync(cancellationToken).ConfigureAwait(false))
  31. {
  32. return HealthCheckResult.Healthy();
  33. }
  34. }
  35. return HealthCheckResult.Unhealthy();
  36. }
  37. }