我有一个简单的asp.net核心Web API,我想为mongodb添加一个运行状况检查,我具有正确的nuget包和有效的连接字符串,通过手动连接到db可以验证它们。
问题是,导航到http://localhost:56103/health
时出现以下异常。 (我本来希望看到包含mongodb的运行状况信息的UI。)
An unhandled exception occurred while processing the request.
InvalidOperationException: Unable to resolve service for type 'System.String' while attempting to activate 'HealthChecks.MongoDb.MongoDbHealthCheck'.
两个问题:
1)设置健康检查和服务时我缺少什么?
2).AddMongoDb( . . .)
是否初始化IMongoClient?它在做类似于services.AddSingleton<IMongoClient>(mongoClient);
的事情吗?
3)我必须添加哪些配置才能获得相似的UI(similar what is shown in this doc)
这是我正在使用的Startup.cs
代码的一部分:
public IServiceProvider ConfigureServices(IServiceCollection services)
{
var config = Configuration.Get<Config>();
ConfigureMvc(services, config);
ConfigureDatabase(services, config);
ConfigureHealthChecks(services, config);
var containerBuilder = ConfigureDependencyResolver();
containerBuilder.Populate(services);
ConfigureLogger(containerBuilder, config);
_container = containerBuilder.Build();
return new AutofacServiceProvider(_container);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//Middleware setups
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHealthChecks("/health", new HealthCheckOptions
{
Predicate = _ => true,
ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
})
.UseHealthChecksUI();
app.UseMvc();
}
private static void ConfigureHealthChecks(IServiceCollection services, Config config)
{
services.AddHealthChecksUI()
.AddHealthChecks()
.AddMongoDb(
config.DatabaseSettings.DatabaseConnectionString,
config.DatabaseSettings.DatabaseName,
null,
tags: null)
.AddCheck<MongoDbHealthCheck>("MongoDb Health Check", null,null);
}
private static void ConfigureDatabase(IServiceCollection services, Config config)
{
var dbConfig = config.DatabaseSettings;
var mongoClient = new MongoClient(dbConfig.DatabaseConnectionString);
var mongoDatabase = mongoClient.GetDatabase(dbConfig.DatabaseName);
services.AddSingleton<IMongoClient>(mongoClient);
services.AddTransient(context => mongoDatabase);
}
答案 0 :(得分:2)
因此,您尝试使用应该通过DI插入的内容。 但是我不确定甚至还需要AddCheck部分。
无论如何,要解决此问题,您需要在DI中添加以下行:
services.AddSingleton(new MongoDbHealthCheck(config.DatabaseSettings.DatabaseConnectionString, config.DatabaseSettings.DatabaseName));