C#C
C#6mo ago
Maik

✅ ASP.NET Core DI: DbContext Not Shared in Scoped Services

I'm working on an ASP.NET Core application using Entity Framework Core. I have a single ApplicationDbContext that implements multiple interfaces, including ISubsetDbContext (for specific DbSet access) and IUnitOfWork (for transaction management).

Based on my understanding, my DI setup is configured to ensure that ISubsetDbContext and IUnitOfWork resolve to the very same instance of ApplicationDbContext within any given request scope. This is because both are registered with a Scoped lifetime and explicitly retrieve ApplicationDbContext via provider.GetRequiredService<ApplicationDbContext>().

public static IServiceCollection AddPersistence(this IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>((serviceProvider, options) =>
    {
        var secretConnectionStringService = serviceProvider.GetRequiredService<ISecretConnectionStringService>();
        options.UseNpgsql(secretConnectionStringService.GetConnectionString());
    });

    
    services.AddScoped<ISubsetDbContext>(provider => provider.GetRequiredService<ApplicationDbContext>());
    services.AddScoped<IUnitOfWork>(provider => provider.GetRequiredService<ApplicationDbContext>());
    
    return services;
}


The unexpected behavior is that when I inject IUnitOfWork into a pipeline behavior and ISubsetDbContext into another service within what I believe to be the same request scope, they appear to be receiving different instances of ApplicationDbContext. This is problematic because a transaction started by IUnitOfWork is then not shared with operations performed through ISubsetDbContext.

Could anyone help me out here? I might just have a big misunderstanding...
Was this page helpful?