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:
services.AddDbContext<MyContext>(options =>
{
options.UseSqlServer("<my-connection-string");
options.RegisterInterceptor<MyInterceptor>().
});
I want to use Azure Managed Identities to connect to an Azure SQL instance.
I'm trying to use a
DbConnectionInterceptorto handle theConnectionOpeningAsync"event" to use the Azure.Identity SDK to grab a token and give it to theSqlConnectioninstance.I'd like some services to be injected into the interceptor, but unfortunately today the
DbContextOptionsBuilder.AddInterceptorsmethod 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
AddInterceptorsmethod works, I found a solution, but it's quite heavy:IDbContextOptionsExtensionDbContextOptionsExtensionInfo, which abstract members are not super obvious in how they need to be impemented((IDbContextOptionsBuilderInfrastructure)options).AddOrUpdateExtension(new MyExtension())asoptions.Options.WithExtension(new MyExtension())doesn't seem to workI'd love for that process to be easier, along the lines of: