作者:潇湘V烟雨 | 来源:互联网 | 2022-12-06 16:30
我正在尝试使用新的ASP.NET Code 2.2 Healthchecks功能.
在.net博客的此链接中,它显示了一个示例:
public void ConfigureServices(IServiceCollection services)
{
//...
services
.AddHealthChecks()
.AddCheck(new SqlConnectionHealthCheck("MyDatabase", Configuration["ConnectionStrings:DefaultConnection"]));
//...
}
public void Configure(IApplicationBuilder app)
{
app.UseHealthChecks("/healthz");
}
我可以添加实现该Microsoft.Extensions.Diagnostics.HealthChecks.IHealthCheck
接口的自定义检查.但是因为我需要向AddCheck
方法提供实例而不是类型,并且需要在ConfigureServices
方法内部运行,所以我不能在自定义检查器中注入任何依赖项.
有没有办法解决这个问题?
1> Shaun Luttin..:
简答
如何在ASP.NET核心运行状况检查中注入依赖项.
如果我们以正确的顺序注册我们的服务,那么SomeDependency
将可以注入SomeHealthCheck
构造函数,并将SomeHealthCheck
作为运行状况检查功能的一部分运行.
public void ConfigureServices(IServiceCollection services)
{
services.AddHealthChecks();
services.AddSingleton();
// register the custom health check
// after AddHealthChecks and after SomeDependency
services.AddSingleton();
}
更多细节
一个健康检查样品中评论说:
所有IHealthCheck服务都可用于健康检查服务和中间件.我们建议将所有健康检查注册为Singleton服务.
完整样本
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Diagnostics.HealthChecks;
public class SomeDependency
{
public string GetMessage() => "Hello from SomeDependency";
}
public class SomeHealthCheck : IHealthCheck
{
public string Name => nameof(SomeHealthCheck);
private readonly SomeDependency someDependency;
public SomeHealthCheck(SomeDependency someDependency)
{
this.someDependency = someDependency;
}
public Task CheckHealthAsync(
CancellationToken cancellatiOnToken= default(CancellationToken))
{
var message = this.someDependency.GetMessage();
var result = new HealthCheckResult(HealthCheckStatus.Failed, null, null, null);
return Task.FromResult(result);
}
}
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddHealthChecks();
services.AddSingleton();
services.AddSingleton();
}
public void Configure(IApplicationBuilder app)
{
app.UseHealthChecks("/healthz");
app.Run(async (context) => await context.Response.WriteAsync("Hello World!"));
}
}
此示例也可以在GitHub上找到.