NuGet Package Architect.EntityFramework.DbContextManagement

Manage your DbContexts the right way.

The persistence layer or infrastructure layer uses the DbContext (e.g.

from a repository). Controlling its scope and transaction lifetime, however, is ideally the reponsibility of the orchestrating layer (e.g.

from an application service). This package adds that ability to Entity Framework Core 5.0.0 and up.

// Register
public void ConfigureServices(IServiceCollection services)
services.AddPooledDbContextFactory(context =>
context.UseSqlServer(connectionString, sqlServer => sqlServer.EnableRetryOnFailure()));


// Consume
public class MyRepository : IMyRepository
// Accesses the DbContext instance currently provided by the orchestrating layer
private MyDbContext DbContext => this.DbContextAccessor.CurrentDbContext;

private IDbContextAccessor DbContextAccessor { get; }

public OrderRepo(IDbContextAccessor dbContextAccessor)
this.DbContextAccessor = dbContextAccessor ?? throw new ArgumentNullException(nameof(dbContextAccessor));

public Task GetOrderById(long id)
return this.DbContext.Orders.SingleOrDefaultAsync(o.Id == id);

// Orchestrate
public class MyApplicationService
private IDbContextProvider DbContextProvider { get; }
private IMyRepository MyRepository { get; }

public MyApplicationService(IDbContextProvider dbContextProvider, IMyRepository myRepository)
this.DbContextProvider = dbContextProvider ?? throw new ArgumentNullException(nameof(dbContextProvider));
this.MyRepository = myRepository ?? throw new ArgumentNullException(nameof(myRepository));

public async Task PerformSomeUnitOfWork()
// Provide a DbContext and execute a block of code within its scope
await this.DbContextProvider.ExecuteInDbContextScopeAsync(async executionScope =>
// Until the end of this block, IDbContextAccessor can access the scoped DbContext
// It can do so from any number of invocations deep (not shown here)
await this.MyRepository.AddOrder(new Order());

// If we have made modifications, we should save them
// We could save here or as part of the repository methods, depending on our preference
await executionScope.DbContext.SaveChangesAsync();
}); // If no exceptions occurred and this scope was not nested in another, the transaction is committed asynchronously here


Version: 1.0.0
Author(s): TheArchitectDev, Timovzl
Last Update: Friday, December 18, 2020
.NET Fiddle: Create the first Fiddle
NuGet Url:

Install-Package Architect.EntityFramework.DbContextManagement
dotnet add package Architect.EntityFramework.DbContextManagement
paket add Architect.EntityFramework.DbContextManagement
Architect.EntityFramework.DbContextManagement Download (Unzip the "nupkg" after downloading)