Search code examples
c#.net-coredependency-injectionentity-framework-coreconfiguration

Using DI in SaveChangesInterceptor


I have an Entity Framework Core interceptor that has to get some configuration that's declared as so:

builder.Services.Configure<AppConfig>(builder.Configuration.GetSection("AppConfig"));

I'm having a hard time registering the interceptor since I can't use the AppConfig when overriding OnConfiguring.

I found a way to add it when configuring services here and followed this SO question. The solution can't work here because (I presume) the AppConfig is only created after building.

var someInterceptor = new SomeInterceptor(/*this takes AppConfig as an argument*/);
builder.Services.AddSingleton(someInterceptor);

....AddInterceptors(someInterceptor);

What can I do with this? Is it possible to inject this into the interceptor?


Solution

  • Actually, in more modern times (.NET6+ with ConfigurationManager) you don't need to build the configuration to get values from it. You can just:

    var appConfig = builder.Configuration.GetSection("AppConfig").Get<AppConfig>();
    var someInterceptor = new SomeInterceptor(appConfig);
    builder.Services.AddSingleton(someInterceptor);
    

    That being said, in the blogpost you linked, there is a cleaner approach used -

    services.AddDbContext<AppDbContext>((provider, options) =>
    {
        options.UseSqlServer(Configuration.GetConnectionString("<connection-string-name>"));
    
        // 3. Resolve the interceptor from the service provider
        options.AddInterceptors(provider.GetRequiredService<AadAuthenticationDbConnectionInterceptor>());
    });
    

    if you make IOptions<AppConfig> (or another options-pattern type with appropriate lifetime for your use case) a dependency of the interceptor it will get resolved correctly.