Skip to content

Ability to register IInterceptor without an IDbContextOptionsExtension #21578

@mderriey

Description

@mderriey

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>().
});

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions