基于具有某个接口的所有服务动态创建健康检查



我有一长组检查数据的服务,它们都在"IDataCheck"接口下。

idatachchecks是一个空接口,只有一个方法"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
}

我现在还想在asp.net核心健康检查中显示这些检查的结果,同样使用healthcheck ui, ref:

  • https://learn.microsoft.com/en us/aspnet/core/host -和- deploy/health checks?view=aspnetcore - 6.0
  • https://github.com/Xabaril/AspNetCore.Diagnostics.HealthChecks

我不想在每次数据检查时手动创建一个healthcheck,否则就没有接口的用处了

我也不想只创建一个healthcheck,否则它会在ui的一个文本列中产生一长串结果,因为它不支持任何格式。


在"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
}

最新更新