3

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?

1 Answer 1

4

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>()); }); 
Sign up to request clarification or add additional context in comments.

1 Comment

Yes of course. I cannot believe I missed that one. Doh! Thanks for pointing me in the right direction :-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.