hsd
hsd

Reputation: 452

Health check for AddDbContextCheck by TContextService and TContextImplementation

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?

Upvotes: 8

Views: 8210

Answers (1)

Euphoric
Euphoric

Reputation: 12849

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

Upvotes: 7

Related Questions