3

我正在使用 .NET Core 3.1 Web 应用程序。安装了以下软件包:

<PackageReference Include="Microsoft.AspNetCore.Diagnostics.HealthChecks" Version="2.2.0" />
<PackageReference Include="AspNetCore.HealthChecks.UI" Version="3.1.2" />

在我的 Startup.cs 类中,我像这样注册我的 HealthChecks:

services.AddHealthChecksUI();
services.AddHealthChecks()
    .AddCheck("SQL Server", new SqlServerConnectionHealthCheck(connectionString), HealthStatus.Unhealthy)
    .AddCheck("Redis", new RedisConnectionHealthCheck(), HealthStatus.Unhealthy)
    .AddCheck("CRM", new CrmConnectionHealthCheck(), HealthStatus.Unhealthy)
    .AddCheck("DMS", new DmsConnectionHealthCheck(), HealthStatus.Unhealthy);

app.UseEndpoints(endpointRouteBuilder =>
{
    endpointRouteBuilder.MapControllers();

    endpointRouteBuilder.MapHealthChecks("/health");
    endpointRouteBuilder.MapHealthChecksUI(options =>
    {
        options.UIPath = "/healthui";
    });
}

可悲的是,一旦我的应用程序启动,我就会收到以下异常:

未处理的异常。System.InvalidOperationException:未注册“HealthChecks.UI.Core.Data.HealthChecksDb”类型的服务。
在 Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType) 在 Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider) 在 HealthChecks.UI.Core.HostedService.UIInitializationHostedService.InitializeDatabase(IServiceProvider sp)在 HealthChecks.UI.Core.HostedService.UIInitializationHostedService.StartAsync(CancellationToken cancelToken) 在 Microsoft.AspNetCore.Hosting.HostedServiceExecutor.ExecuteAsync(Func`2 回调,布尔 throwOnFirstFailure) 在 Microsoft.AspNetCore.Hosting.WebHost.StartAsync(CancellationToken cancelToken) 在Microsoft.AspNetCore 上的 Microsoft.AspNetCore.Hosting.WebHostExtensions.RunAsync(IWebHost 主机,CancellationToken 令牌,字符串 startupMessage)。Hosting.WebHostExtensions.RunAsync(IWebHost host, CancellationToken token, String startupMessage) at Microsoft.AspNetCore.Hosting.WebHostExtensions.RunAsync(IWebHost host, CancellationToken token) at Microsoft.AspNetCore.Hosting.WebHostExtensions.Run(IWebHost host)
在 C:\Repos***\Program.cs:line 26 中的 fzag.portal.api.Program.Main(String[] args)

此异常仅在使用AddHealthChecksUI(). 我认为 API 正在尝试持久化数据,因此它会搜索HealthChecksDb(这是一个 DbContext)的一个实例。但是为什么不AddHealthChecksUI()注册 DbContext 本身呢?我做错了什么?

4

1 回答 1

3

您需要指定 HealthCheckUI 的数据应保存在何处。这是一个使用 SQL Server 的示例:

services.AddHealthChecksUI().AddSqlServerStorage(Configuration.GetConnectionString("HealthChecks"));

新添加的包是:

<PackageReference Include="AspNetCore.HealthChecks.UI.SqlServer.Storage" Version="3.1.2" />

有不同的提供程序可用,每个都来自另一个 Nuget 包。您可以在此处找到更多信息:https ://github.com/Xabaril/AspNetCore.Diagnostics.HealthChecks#ui-storage-providers

于 2020-11-20T10:40:21.190 回答