Health check for AddDbContextCheck by TContextService and TContextImplementation

asp.net-core c# entity-framework-core

Question

I'm setup my DBContext by TContextService and TContextImplementation options. Something like this:

services.AddDbContext<IMyDbContext, MyDbContext>(options => options.UseNpgsql(myDatabaseConnectionString));

I try to enable health check from Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore When I try to use this code

services.AddHealthChecks().AddDbContextCheck<MyDbContext>() I got from health end point response that

InvalidOperationException: Unable to resolve service for type 'MyDbContext' while attempting to activate 'Microsoft.Extensions.Diagnostics.HealthChecks.DbContextHealthCheck`1[MyDbContext]'. Microsoft.Extensions.DependencyInjection.ActivatorUtilities+ConstructorMatcher.CreateInstance(IServiceProvider provider) Microsoft.Extensions.DependencyInjection.ActivatorUtilities.CreateInstance(IServiceProvider provider, Type instanceType, object[] parameters) Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetServiceOrCreateInstance(IServiceProvider provider)

Do you know any method to use two options TContextService and TContextImplementation for health check by Entity Framework?

1
2
9/17/2019 3:01:08 PM

Accepted Answer

You seem to have hit a case where the two cannot work together. I think you have two options:

First is to register the DbContext directly and then just resolve the interface from this registration.

services.AddDbContext<MyDbContext>(options => options.UseNpgsql(myDatabaseConnectionString));
services.AddTransient<IMyDbContext>(c=>c.GetRequiredService<MyDbContext>());

Another option is to implement the health check functionality yourself. Which is not exactly hard.

See : EntityFrameworkCoreHealthChecksBuilderExtensions.cs and DbContextHealthCheck.cs

2
9/17/2019 3:15:35 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow