gpt4 book ai didi

c# - 基于具有特定接口(interface)的所有服务动态创建健康检查

转载 作者:行者123 更新时间:2023-12-05 05:39:23 24 4
gpt4 key购买 nike

我有一长串检查数据的服务,并且都在“IDataCheck”接口(interface)下。

IDataChecks 是一个空接口(interface),只有一个方法“runCheckAsync”

在命令行应用程序中我这样做:

IEnumerable<IDataCheck>? services = _serviceProvider.GetServices<IDataCheck>();
foreach (IDataCheck? s in services)
{
DataCheckResult result = await s.RunCheckAsync();
// all kinds of stuff with the result such as proposing to autofix
}

我现在还想使用 healthcheck ui 在 asp.net core healtchecks 中显示这些检查的结果,引用:

我不想为每个数据检查手动创建健康检查,否则拥有接口(interface)的用处就没有了

我也不想只创建一个健康检查,否则它会在用户界面的一个纯文本列中生成一长串结果,因为它不支持任何格式。

最佳答案


在“WebApplication app = builder.Build();”之前的行中,在 Guru 的评论的帮助下解决了这个问题打电话:

public static IServiceCollection AddDataHealthChecks(this IServiceCollection services)
{
List<string> dataCheckClassList = new List<string>();
IEnumerable<ServiceDescriptor>? dataServices = services.Where(x => x.ServiceType == typeof(IDataCheck));
foreach (ServiceDescriptor s in dataServices)
{
var fullName = s.ImplementationType?.FullName;
if (fullName is not null)
{
dataCheckClassList.Add(fullName);
}
}
foreach(string fullName in dataCheckClassList)
{
services
.AddHealthChecks()
.AddTypeActivatedCheck<DataQualityHealthCheck>(fullName,
failureStatus: HealthStatus.Degraded,
tags: new[] { "data" },
args: new object[] { fullName });
}

return services;
}

然后在健康检查中:

IDataCheck? service = _serviceProvider
.GetServices<IDataCheck>().FirstOrDefault(x => (x.ToString() == _dataCheckServiceName));
if (service is not null)
{
DataCheckResult result = await service.RunCheckAsync();
// etc
}

关于c# - 基于具有特定接口(interface)的所有服务动态创建健康检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72704438/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com