【问题标题】:.NET Core health check: Unable to find the required services.NET Core 运行状况检查:找不到所需的服务
【发布时间】: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&lt;CustomHealthCheck&gt;("Storage", null, null, new TimeSpan(0, 1, 0));
  • 我使用的是 3.1 版。

标签: .net-core health-check


【解决方案1】:

我刚刚重温了一遍。问题是第一个使用 nuget 包Microsoft.AspNetCore.HeatlhChecks。它应该使用nuget包Microsoft.AspNetCore.Diagnostics.HealthChecks

令人困惑的是,这两个包的名称非常相似,并且都定义了接口IHealthCheck,因此上面的代码不会生成编译器错误消息。它只是抛出一个错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-25
    • 2018-08-13
    • 1970-01-01
    • 2020-09-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多