.NET Core HealthCheck - 添加带有依赖注入和参数的 HealthCheck

Els*_*nia 1 c# dependency-injection .net-core-3.1 health-check

我有继承基类的不同类。基类实现接口 IHealthCheck。每个类都有一个构造函数,根据类需要一个记录器和参数。例如 :

public ConnectionHealthCheck(ILogger logger, string address)
        : base(logger)
    {
         Address = address;
    }
Run Code Online (Sandbox Code Playgroud)

我有一个 appSettings.json,它允许我配置多个诊断以在我的健康检查服务中执行。

我在 App.xaml.cs 中获得了诊断列表,我正在尝试将它们添加到 HealthCheck 列表中。

问题是我不能用它旁边的参数进行依赖注入,我不知道什么是最好的解决方案......

这是我的代码的一些部分。

OnStartup 方法:

protected override void OnStartup(StartupEventArgs e)
    {
        var a = Assembly.GetExecutingAssembly();
        using var stream = a.GetManifestResourceStream("appsettings.json");

        Configuration = new ConfigurationBuilder()
            .AddJsonStream(stream)
            .Build();

        var host = new HostBuilder()
            .ConfigureHostConfiguration(c => c.AddConfiguration(Configuration))
                .ConfigureServices(ConfigureServices)
                .ConfigureLogging(ConfigureLogging)
                .Build();
       [...] }
Run Code Online (Sandbox Code Playgroud)

configureService 方法:

private void ConfigureServices(IServiceCollection serviceCollection)
    {
        // create and add the healthCheck for each diag in the appSettings file
        List<DiagnosticConfigItem> diagnostics = Configuration.GetSection("AppSettings:Diagnostics").Get<List<DiagnosticConfigItem>>();
        diagnostics.ForEach(x => CreateHealthCheck(serviceCollection, x)); 
        [...] }
Run Code Online (Sandbox Code Playgroud)

方法 CreateHealthCheck 问题出在哪里:

private void CreateHealthCheck(IServiceCollection serviceCollection, DiagnosticConfigItem configItem)
    {
        EnumDiagType type;

        try
        {
            type = (EnumDiagType)Enum.Parse(typeof(EnumDiagType), configItem.Type, true);
        }
        catch (Exception)
        {
            throw new Exception("Diagnostic type not supported");
        }

        switch (type)
        {
            case EnumDiagType.Connection:
                serviceCollection.AddHealthChecks().AddCheck(nameof(ConnectionHealthCheck), new ConnectionHealthCheck(???, configItem.Value));
                break;
            case EnumDiagType.Other:
                [...] }
Run Code Online (Sandbox Code Playgroud)

如您所见,我无法创建 ConnectionHealthCheck 类的实例,因为我无法访问 ILogger 对象...

那么我该怎么做呢?我想过不同的解决方案,但我没有答案或方法

  • 不在 App.xaml.cs 中构建 HealthCheck 服务,而是在 ? (例如,在我可以访问 serviceCollection 和记录器的视图模型中)

  • 找到一种方法让记录器在 CreateHealthCheck 方法中使用它?

  • 做类似的事情,但我不知道什么时候可以传递参数

    serviceCollection.AddHealthChecks().AddCheck<ConnectionHealthCheck>(nameof(ConnectionHealthCheck));

Gur*_*ron 5

您可以使用HealthCheckRegistration注册您的类(它应该实现IHealthCheck),它具有接受委托的构造函数Func<IServiceProvider,IHealthCheck>,允许您使用IServiceProvider解析所需的参数来创建您的健康检查类的实例。像这样的东西:

public static class ConnectionHealthCheckBuilderExtensions
{
    const string DefaultName = "example_health_check";

    public static IHealthChecksBuilder AddConnectionHealthCheck(
        this IHealthChecksBuilder builder,
        string name = default,
        DiagnosticConfigItem configItem,
        HealthStatus? failureStatus = default,
        IEnumerable<string> tags = default)
    {
        return builder.Add(new HealthCheckRegistration(
            name ?? DefaultName,
            sp => new ConnectionHealthCheck(sp.GetRequiredService<ISomeService>(), configItem.Value),
            failureStatus,
            tags));
    }
}
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,请参阅文档的这一部分。