You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Ability to register IInterceptor without an IDbContextOptionsExtension #21578
I want to use Azure Managed Identities to connect to an Azure SQL instance.
I'm trying to use a DbConnectionInterceptor to handle the ConnectionOpeningAsync "event" to use the Azure.Identity SDK to grab a token and give it to the SqlConnection instance.
I'd like some services to be injected into the interceptor, but unfortunately today the DbContextOptionsBuilder.AddInterceptors method accepts constructed instances only.
I tried registering interceptors in the application service provider, but they're not picked up by EF Core.
While reverse-engineering how the AddInterceptors method works, I found a solution, but it's quite heavy:
Need to create a class that implements IDbContextOptionsExtension
Need to create a class that derives from DbContextOptionsExtensionInfo, which abstract members are not super obvious in how they need to be impemented
((IDbContextOptionsBuilderInfrastructure)options).AddOrUpdateExtension(new MyExtension()) as options.Options.WithExtension(new MyExtension()) doesn't seem to work
I'd love for that process to be easier, along the lines of:
Reacted by Thomas Boby, cocowalla, Kon Stormozhev, Eric Sampson, keatkeat87, Hallvard Molin Morstøl, Greg Bachraty, Ashish Patel, Weihan Li, WanWan93 and 1 more
@mderriey Agreed that this would be a useful feature. Interceptors can be resolved from the internal service provider, but it's currently not easy to do it from application provider.
but it's currently not easy to do it from application provider
How would one achieve this? And are there any gotchas in doing so?
I've done some research over the WE, and I realised that many common services are not registered in the internal service provider — in my case, I couldn't inject ILogger<T> in the interceptor because it's not registered, so I had to use the scoped ILoggerFactory.
@mderriey CoreOptionsExtension contains a reference to the ApplicationServiceProvider. In addition, this PR has some useful information on the internal service provider: dotnet/EntityFramework.Docs#2066
Would you say the following approach is OK to resolve interceptors from the application service provider?
// Startup.cspublicvoidConfigureServices(IServiceCollectionservices){// Register interceptor as itself so we can resolve it in the extensionservices.AddScoped<AadAuthenticationDbConnectionInterceptor>();// Register DbContext and add custom extensionservices.AddDbContext<AppDbContext>(options =>{options.UseSqlServer(Configuration.GetConnectionString("UserDb"));((IDbContextOptionsBuilderInfrastructure)options).AddOrUpdateExtension(newAppOptionsExtension());});}// AppOptionsExtension.cspublicclassAppOptionsExtension:IDbContextOptionsExtension{privateDbContextOptionsExtensionInfo_info;publicDbContextOptionsExtensionInfoInfo=>_info??=newExtensionInfo(this);publicvoidApplyServices(IServiceCollectionservices){services.AddScoped<IInterceptor>(provider =>{// Get application service provider from CoreOptionsExtensionvarapplicationServiceProvider=provider.GetRequiredService<IDbContextOptions>().FindExtension<CoreOptionsExtension>().ApplicationServiceProvider;// Resolve interceptor, and register in internal service provider as IInterceptorreturnapplicationServiceProvider.GetRequiredService<AadAuthenticationDbConnectionInterceptor>();});}publicvoidValidate(IDbContextOptionsoptions){}privateclassExtensionInfo:DbContextOptionsExtensionInfo{publicExtensionInfo(IDbContextOptionsExtensionextension):base(extension){}publicoverrideboolIsDatabaseProvider=>false;publicoverridestringLogFragment=>null;publicoverridelongGetServiceProviderHashCode()=>0L;publicoverridevoidPopulateDebugInfo(IDictionary<string,string>debugInfo){}}}// AadAuthenticationDbConnectionInterceptor.cspublicclassAadAuthenticationDbConnectionInterceptor:DbConnectionInterceptor{privatereadonlyILogger_logger;// Could also inject whatever other service here as they'd be resolved from the application service providerpublicAadAuthenticationDbConnectionInterceptor(ILogger<AadAuthenticationDbConnectionInterceptor>logger){_logger=logger;}publicoverrideasyncTask<InterceptionResult>ConnectionOpeningAsync(DbConnectionconnection,ConnectionEventDataeventData,InterceptionResultresult,CancellationTokencancellationToken){varsqlConnection=(SqlConnection)connection;//// Only try to get a token from AAD if// - We connect to an Azure SQL instance; and// - The connection doesn't specify a username.//varconnectionStringBuilder=newSqlConnectionStringBuilder(sqlConnection.ConnectionString);if(connectionStringBuilder.DataSource.Contains("database.windows.net",StringComparison.OrdinalIgnoreCase)&&string.IsNullOrEmpty(connectionStringBuilder.UserID)){try{sqlConnection.AccessToken=awaitGetAzureSqlAccessToken(cancellationToken);_logger.LogInformation("Successfully acquired a token to connect to Azure SQL");}catch(Exceptione){_logger.LogError(e,"Unable to acquire a token to connect to Azure SQL");}}else{_logger.LogInformation("No need to get a token");}returnawaitbase.ConnectionOpeningAsync(connection,eventData,result,cancellationToken);}privatestaticasyncTask<string>GetAzureSqlAccessToken(CancellationTokencancellationToken){if(RandomNumberGenerator.GetInt32(10)>=5){thrownewException("Faking an exception while tying to get a token to make sure errors are logged");}// See https://docs.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/services-support-managed-identities#azure-sqlvartokenRequestContext=newTokenRequestContext(new[]{"https://database.windows.net//.default"});vartokenRequestResult=awaitnewDefaultAzureCredential().GetTokenAsync(tokenRequestContext,cancellationToken);returntokenRequestResult.Token;}}
Quick update as I found a much easier solution. It's embarrassing I didn't find that before.
Using the AddDbContext overloads that take an Action<IServiceProvider, DbContextOptionsBuilder> makes resolving the interceptors from the application service provider super easy, without having to register an extension with all the plumbing code that goes with it.
Here's a quick sample:
publicclassStartup{publicStartup(IConfigurationconfiguration){Configuration=configuration;}publicIConfigurationConfiguration{get;}publicvoidConfigureServices(IServiceCollectionservices){// 1. Register the interceptor in the dependency injection containerservices.AddSingleton<AadAuthenticationDbConnectionInterceptor>();// 2. Use one of the overload of AddDbContext that takes a parameter of type Action<IServiceProvider, DbContextOptionsBuilder>services.AddDbContext<AppDbContext>((provider,options)=>{options.UseSqlServer(Configuration.GetConnectionString("<connection-string-name>"));// 3. Resolve the interceptor from the service provideroptions.AddInterceptors(provider.GetRequiredService<AadAuthenticationDbConnectionInterceptor>());});}}publicclassAadAuthenticationDbConnectionInterceptor:DbConnectionInterceptor{// Implementation ommitted for brevity}
@mderriey The main point of this issue is allowing registration of an interceptor when you don't control the AddDbContext or OnConfigurng code. Sorry we didn't point out earlier that this can be done in AddDbContext.
Activity
ajcvickers commentedon Jul 10, 2020
@mderriey Agreed that this would be a useful feature. Interceptors can be resolved from the internal service provider, but it's currently not easy to do it from application provider.
AndriySvyryd commentedon Jul 10, 2020
But this particular scenario would be handled better by #13261
mderriey commentedon Jul 13, 2020
How would one achieve this? And are there any gotchas in doing so?
I've done some research over the WE, and I realised that many common services are not registered in the internal service provider — in my case, I couldn't inject
ILogger<T>in the interceptor because it's not registered, so I had to use the scopedILoggerFactory.ajcvickers commentedon Jul 13, 2020
@mderriey CoreOptionsExtension contains a reference to the ApplicationServiceProvider. In addition, this PR has some useful information on the internal service provider: dotnet/EntityFramework.Docs#2066
mderriey commentedon Jul 14, 2020
Thanks for the pointer!
Would you say the following approach is OK to resolve interceptors from the application service provider?
ajcvickers commentedon Jul 16, 2020
@mderriey Looks reasonable.
mderriey commentedon Jul 16, 2020
Thanks
mderriey commentedon Sep 16, 2020
Hey folks 👋
Quick update as I found a much easier solution. It's embarrassing I didn't find that before.
Using the
AddDbContextoverloads that take anAction<IServiceProvider, DbContextOptionsBuilder>makes resolving the interceptors from the application service provider super easy, without having to register an extension with all the plumbing code that goes with it.Here's a quick sample:
I've blogged about that and a couple of other things over at https://purple.telstra.com/blog/a-better-way-of-resolving-ef-core-interceptors-with-dependency-injection.
ajcvickers commentedon Sep 16, 2020
@mderriey The main point of this issue is allowing registration of an interceptor when you don't control the AddDbContext or OnConfigurng code. Sorry we didn't point out earlier that this can be done in AddDbContext.