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?
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>());
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With