【发布时间】:2021-05-30 04:22:13
【问题描述】:
我正在尝试使用 Startup.cs 中的代码在示例 .NET Core 应用程序检查中注册运行状况:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
// Adding healthcheck in ConfigureServices
services.AddHealthChecks(checks =>
{
// Custom health check which implements IHealthCheck
// Breakpoint hits here and this code is executed
checks.AddCheck<CustomHealthCheck>("Storage", new TimeSpan(0, 1, 0));
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
// This throws the exception: "Unable to find the required services..."
endpoints.MapHealthChecks("/health");
});
// I've tried this too. This also throws an exception
app.UseHealthChecks("/health");
}
但是,当我运行应用程序时,出现异常:“无法找到所需的服务。请通过在调用 'ConfigureServices(...)' 中调用 'IServiceCollection.AddHealthChecks' 添加所有需要的服务应用程序启动代码。”
我发现此异常消息令人困惑,因为我在 ConfigureServices 方法中调用 AddHealthChecks。所以我不确定我是否犯了一个错误,或者我是否需要做其他事情。
任何建议表示赞赏。
【问题讨论】:
-
您使用的是哪个 .NET Core 版本?我无法使用 .NET 5 重现它,但语法略有不同:
services.AddHealthChecks().AddCheck<CustomHealthCheck>("Storage", null, null, new TimeSpan(0, 1, 0)); -
我使用的是 3.1 版。