我有继承自基类的不同类。基类实现接口IHealthCheck。每个类都有一个构造函数,该构造函数需要一个记录器和根据该类的参数。例如 :
public ConnectionHealthCheck(ILogger logger, string address)
: base(logger)
{
Address = address;
}
我有一个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();
[...] }
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));
[...] }
而方法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:
[...] }
如您所见,由于无法到达ILogger对象,因此无法创建ConnectionHealthCheck类的实例。
那我该怎么办呢?我考虑了不同的解决方案,但没有答案或解决方法
不是在App.xaml.cs中而是在?之后构建HealthCheck服务。(在一个示例模型中,我可以访问serviceCollection和logger)
找到一种方法使记录器在CreateHealthCheck方法中使用它?
做这样的事情,但我不知道何时可以传递参数
serviceCollection.AddHealthChecks().AddCheck<ConnectionHealthCheck>(nameof(ConnectionHealthCheck));
您可以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));
}
}
有关更多详细信息,请参见文档的此部分。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句