You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

内部IServiceCollection中IHealthCheckPublisher的注册与触发实现

解决内部库触发健康检查的方案

自动定时触发(和WebApplication行为一致)

ASP.NET Core的WebApplication会自动注册HealthCheckPublisherHostedService来定时执行健康检查并通过IHealthCheckPublisher发布结果。你的内部库没有WebApplication,只需手动注册这个托管服务即可:

步骤1:添加健康检查托管服务

在应用级IServiceCollection的注册代码中,补充添加托管服务:

services.Configure<HealthCheckPublisherOptions>(extensions.ConfigurationCore.HealthCheckOptionsSetup);

services.AddSingleton<IHealthCheckPublisher, ConnectionHealthCheck>()
    .AddHealthChecks()
    .AddCheck<ConnectionHealthCheck>("[].[HealthCheck]");

// 手动添加健康检查定时发布的托管服务
services.AddHostedService<HealthCheckPublisherHostedService>();

这个类位于Microsoft.Extensions.Diagnostics.HealthChecks命名空间下,确保项目已引用对应的NuGet包。

步骤2:确保配置匹配

你的内部库通过UseConnectionHealthChecks设置了Delay和Period,需要确保这些配置和HealthCheckPublisherOptions中的设置一致,或者直接通过Configure<HealthCheckPublisherOptions>覆盖统一配置:

services.Configure<HealthCheckPublisherOptions>(options =>
{
    options.Delay = TimeSpan.FromMilliseconds(30_000);
    options.Period = TimeSpan.FromMilliseconds(60_000);
    // 其他选项如Timeout等按需配置
});

按需手动触发

如果不需要定时自动执行,而是在内部库的特定逻辑中触发健康检查,可以直接注入IHealthCheckService手动调用:

步骤1:在内部服务中注入并调用

public class InternalInfrastructure
{
    private readonly IHealthCheckService _healthCheckService;
    private readonly ILogger<InternalInfrastructure> _logger;

    // 构造函数注入IHealthCheckService
    public InternalInfrastructure(IConfiguration configuration, ConfigurationDefinition definition, 
        IHealthCheckService healthCheckService, ILogger<InternalInfrastructure> logger)
    {
        // 原有初始化逻辑
        _healthCheckService = healthCheckService;
        _logger = logger;
    }

    // 按需触发健康检查的方法
    public async Task RunConnectionHealthCheckAsync(CancellationToken cancellationToken = default)
    {
        var healthResult = await _healthCheckService.CheckHealthAsync(cancellationToken);
        
        // 根据结果处理逻辑,比如记录日志、触发重连等
        if (healthResult.Status == HealthStatus.Unhealthy)
        {
            _logger.LogError("连接健康检查失败:{Details}", 
                string.Join("; ", healthResult.Entries.Select(e => $"{e.Key}: {e.Value.Description}")));
            // 触发你的重连或其他恢复逻辑
        }
    }
}

步骤2:确保内部服务提供者包含健康检查服务

你的InternalServiceProvider在复制服务时,需要确保IHealthCheckService等相关服务被包含,调整筛选逻辑:

services.Where(service => 
    service.ServiceType.AssemblyQualifiedName!.StartsWith("Microsoft.") ||
    service.ServiceType == typeof(IHealthCheckService) ||
    service.ServiceType == typeof(IOptions<HealthCheckPublisherOptions>) ||
    service.ServiceType == typeof(IHealthCheckPublisher))
.ForEach(serviceDescriptor => internalServices.Add(serviceDescriptor));

注意事项

  • 确保项目引用Microsoft.Extensions.Diagnostics.HealthChecks和Microsoft.Extensions.Hosting NuGet包(托管服务依赖)。
  • 如果使用手动触发,需要在内部库的合适时机(比如连接失败后、定时任务中)调用健康检查方法。

内容的提问来源于stack exchange,提问作者user22872465

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 01:46:16