Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AddDbContextPool together with AddInterceptors problem

I have used AddDbContext() method to register my EF DbContext classes using DI. It works well, and I can also add an interceptor like this:

        services.AddDbContext<TContextService, TContextImplementation>((provider, opt) =>
        {
            opt.EnableSensitiveDataLogging(enableSensitiveLogging);
            opt.AddInterceptors(provider.GetRequiredService<AzureAdAuthenticationDbConnectionInterceptor>());
        });

Note the first parameter in the optionsAction being a provider. This allows me to add an interceptor like above.

However, now I'd like to use the AddDbContextPool instead. The optionsAction no longer gives me the provider.

        services.AddDbContextPool<TContextService, TContextImplementation>(opt =>
        {
            opt.EnableSensitiveDataLogging(enableSensitiveLogging);
            opt.AddInterceptors(???.GetRequiredService<AzureAdAuthenticationDbConnectionInterceptor>());
        });

..and at this stage I cannot 'new' up an instance of my interceptor. And I don't want to call services.BuildServiceProvider() here either.

So, long story short: how can I achieve the same thing with AddDbContextPool as I can with AddDbContext()?

I guess I can inject an IServiceProvider in some class and do a late resolve, but wanted to check if anyone else has faced this challenge?

like image 766
Henrik Oscarsson Avatar asked Apr 27 '26 21:04

Henrik Oscarsson


1 Answers

The AddDbContextPool extension method has an overload that passes both an IServiceProvider and a DbContextOptionsBuilder argument via the optionsAction.

public static IServiceCollection AddDbContextPool<TContextService,TContextImplementation> (
    this IServiceCollection serviceCollection, 
    Action<IServiceProvider, DbContextOptionsBuilder> optionsAction, 
    int poolSize = 1024
) 
where TContextService : class 
where TContextImplementation : DbContext, TContextService

Your code would look like below

services.AddDbContextPool<TContextService, TContextImplementation>((serviceProvider, opt) =>
{            
    opt.EnableSensitiveDataLogging(enableSensitiveLogging);
    opt.AddInterceptors(serviceProvider.GetRequiredService<AzureAdAuthenticationDbConnectionInterceptor>());
});
like image 164
pfx Avatar answered Apr 30 '26 10:04

pfx