using MCVIngenieros.Healthchecks.__; using MCVIngenieros.Healthchecks.__.__Controllers; using MCVIngenieros.Healthchecks.Abstracts; using MCVIngenieros.Healthchecks.Options; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Options; using System.Reflection; namespace MCVIngenieros.Healthchecks; // Extension methods for IServiceCollection public static class HealthCheckServiceCollectionExtensions { private static IServiceCollection AddHealthChecksSupport(this IServiceCollection services, HealthCheckContainerOptions options) { ArgumentNullException.ThrowIfNull(services, nameof(services)); services.AddSingleton(); services.AddSingleton(Microsoft.Extensions.Options.Options.Create(options)); services.AddCheck(); services.AddControllers().AddApplicationPart(typeof(HealthCheckController).Assembly); return services; } public static IServiceCollection AddHealthChecksSupport(this IServiceCollection services) { ArgumentNullException.ThrowIfNull(services, nameof(services)); var options = new HealthCheckContainerOptions(); var scope = services.BuildServiceProvider().CreateScope(); var config = scope.ServiceProvider.GetRequiredService(); scope.Dispose(); services.Configure(nameof(HealthCheckOptions), config.GetSection(nameof(HealthChecksConfigs))); scope = services.BuildServiceProvider().CreateScope(); var hcopts = scope.ServiceProvider .GetRequiredService>().Get(nameof(HealthCheckOptions)); scope.Dispose(); if (!string.IsNullOrWhiteSpace(hcopts.CacheDuration) && TimeSpan.TryParse(hcopts.CacheDuration, out TimeSpan cacheDuration)) { options.CacheDuration = cacheDuration; } if (!string.IsNullOrWhiteSpace(hcopts.Timeout) && TimeSpan.TryParse(hcopts.Timeout, out TimeSpan timeout)) { options.Timeout = timeout; } if (hcopts.AssembliesToScan != null && hcopts.AssembliesToScan.Length > 0) { options.AssembliesToScan = hcopts.AssembliesToScan.Select(Assembly.Load); } return services.AddHealthChecksSupport(options); } public static IServiceCollection AddHealthChecksSupport(this IServiceCollection services, Action? configure = null) { ArgumentNullException.ThrowIfNull(services, nameof(services)); ArgumentNullException.ThrowIfNull(configure, nameof(configure)); var options = new HealthCheckContainerOptions(); configure?.Invoke(options); return services.AddHealthChecksSupport(options); } public static IServiceCollection AddHealthCheck(this IServiceCollection services) where T : class, IHealthCheck => services.AddCheck(); public static IServiceCollection AddCheck(this IServiceCollection services) where T : class, IHealthCheck { services.TryAddTransient(); return services; } public static IServiceCollection DiscoverHealthChecks(this IServiceCollection services) { // This will trigger the discovery when the container is built var provider = services.BuildServiceProvider(); var container = provider.GetRequiredService(); container.DiscoverHealthChecks(); return services; } }