Unit of Work in .NET: tracking changes and committing them as one transaction, EF Core's change tracker and SaveChangesAsync as the built-in UoW (implicit transaction, identity map), explicit transactions with BeginTransactionAsync for multiple SaveChanges or ExecuteUpdate/ExecuteDelete/raw SQL, wrapping them in CreateExecutionStrategy().ExecuteAsync when EnableRetryOnFailure is on, TransactionScope caveats, and sharing one scoped DbContext across repositories.
Unit of Work records every change made during one business operation and commits them together or not at all.
In EF Core, DbContext is the unit of work. The change tracker records added, modified and deleted entities. One SaveChangesAsync sends them all in a single implicit transaction. That's why every repository in a request must share the same scoped DbContext: separate contexts mean separate commits.
You need an explicit transaction (Database.BeginTransactionAsync) when one operation spans several SaveChanges calls, ExecuteUpdate/ExecuteDelete (which run immediately and skip the change tracker) or raw SQL. With EnableRetryOnFailure, wrap that transaction in CreateExecutionStrategy().ExecuteAsync, and make the block safe to re-run.
The trade-off: one context per request gives you atomic commits, but a long-lived context grows its change tracker and holds stale data.
"Unit of Work comes from Fowler's Patterns of Enterprise Application Architecture: an object keeps a list of everything a business operation changed, and at the end it writes all of it in one transaction. Either the order, its stock reservation and its audit row are all saved, or none are. You don't call the database on every property change, and you don't end up with half an operation saved.
EF Core's
DbContextis exactly that. When I load anOrder, the change tracker takes a snapshot; when I callorder.Submit()and add aStockReservation, it knows one entity is Modified and one is Added.SaveChangesAsyncworks out the SQL, opens a transaction if none is active, sends the commands (batched), and commits. The change tracker is also an identity map, so loading the same order twice in one context gives me the same instance. The consequence for design is that every repository and handler in a request must use the sameDbContext. EF'sAddDbContextregisters it as scoped, so repositories registered as scoped get that one instance. If a repository created its own context, or was a singleton holding one, I'd have two units of work and two commits.The default isn't always enough. If I need two
SaveChangesAsynccalls, say to get a database-generated value before the next step, or I mix inExecuteUpdateAsync,ExecuteDeleteAsyncorExecuteSqlAsync, I open an explicit transaction withDatabase.BeginTransactionAsync. ThoseExecute*methods run immediately and bypass the change tracker, so without that transaction they commit on their own. On Azure SQL I usually haveEnableRetryOnFailureon, and then EF refuses a user-started transaction unless it runs insideCreateExecutionStrategy().ExecuteAsync. The whole block can re-run after a transient failure, so it has to be repeatable. The mistake I see is wrapping EF in a hand-writtenIUnitOfWorkwith its own transaction management that duplicatesSaveChanges.DbContextalready is the unit of work; my job is to keep it to one per operation and to know when the implicit transaction isn't enough."
| Situation | What to use |
|---|---|
| All changes tracked, one commit | SaveChangesAsync (implicit transaction) |
Several SaveChangesAsync calls must be atomic |
BeginTransactionAsync + CommitAsync |
ExecuteUpdateAsync/ExecuteDeleteAsync/ExecuteSqlAsync with tracked changes |
Explicit transaction |
EnableRetryOnFailure + explicit transaction |
CreateExecutionStrategy().ExecuteAsync(...) around it |
| Two databases or a database plus a broker | Not a UoW problem: use the outbox, not distributed transactions |
| State | Set by | SQL on save |
|---|---|---|
Added |
Add |
INSERT |
Modified |
Property change detected (snapshot compare) | UPDATE of changed columns only |
Deleted |
Remove |
DELETE |
Unchanged |
Loaded, nothing changed | None |
Detached |
Not tracked | None |
A stock-reservation endpoint used ExecuteUpdateAsync to decrement stock and then SaveChangesAsync for the order. Under load, about 1 in 2,000 orders failed on save after the stock had already been decremented, leaving phantom reservations. Wrapping both in one explicit transaction inside the execution strategy brought the mismatch to zero in the next month's stock reconciliation.
Checks whether the candidate understands that DbContext is the unit of work, why the context must be shared within an operation, and when the implicit transaction isn't enough.
Green flags
DbContext + SaveChanges is the unit of work with an implicit transaction.ExecuteUpdate/ExecuteDelete bypass the change tracker and commit immediately.EnableRetryOnFailure and repeatable blocks.Red flags
SaveChanges in every repository method.DbContext with its own transaction logic.TransactionScope is the default answer. Business operation (one request / one message)
|
| register new / dirty / removed objects
v
Unit of Work --- commit() ---> BEGIN TRAN
(list of changes) INSERT ... UPDATE ... DELETE ...
COMMIT (or ROLLBACK on any failure)
Fowler lists the responsibilities: register new, dirty and removed objects, then commit them in the right order inside one transaction. A related pattern, Identity Map, ensures each row is loaded into one object per unit of work.
DetectChanges (called automatically by SaveChanges) compares current values to the snapshot.MaxBatchSize).SaveChanges creates one and commits it; any failure rolls back everything.FindAsync checks the tracker before querying; tracking queries return the existing instance for a key.AddDbContext registers DbContext as scoped: one per HTTP request, or per IServiceScope you create in a background worker or message handler. Repositories registered as scoped receive the same instance. Pitfalls:
DbContext isn't thread-safe).IDbContextFactory in Blazor Server or parallel work: each CreateDbContext() is a separate unit of work, on purpose.await using var tx = await db.Database.BeginTransactionAsync(ct);
// several SaveChangesAsync / ExecuteUpdateAsync / ExecuteSqlAsync
await tx.CommitAsync(ct); // disposing without commit rolls back
The default isolation is the database's (READ COMMITTED on SQL Server; Azure SQL has READ_COMMITTED_SNAPSHOT on by default). You can pass an IsolationLevel. Savepoints (CreateSavepointAsync) allow partial rollback; EF uses them automatically when SaveChanges runs inside your transaction.
EnableRetryOnFailure retries transient SQL errors (deadlocks, failovers, throttling). Retrying a single SaveChanges is safe, but EF can't retry half of your hand-opened transaction, so it throws unless you run the whole unit inside strategy.ExecuteAsync(...). That delegate may run more than once, so:
TransactionScopeTransactionScope gives an ambient transaction. In async code you must pass TransactionScopeAsyncFlowOption.Enabled, and spanning two connections can escalate to a distributed transaction. On .NET (Core) distributed transactions are supported only on Windows (since .NET 7) and aren't supported by Azure SQL Database. For a database plus a message broker, use the outbox pattern.
IUnitOfWork?Only to keep SaveChanges out of repositories and the application layer free of DbContext. Let DbContext implement it (Task<int> SaveChangesAsync(CancellationToken) already matches). A hand-written UoW that manages its own transactions and repository instances duplicates EF and usually gets disposal or retries wrong.
LogTo and call SaveChangesAsync with three changes; find the BEGIN TRANSACTION/COMMIT and the batch.DbContext; make the second save fail and observe the partial write.ExecuteUpdateAsync and SaveChangesAsync without a transaction, throw between them, and inspect the data; then fix with BeginTransactionAsync.EnableRetryOnFailure, open a transaction without the execution strategy, and read the exception.BackgroundService, process 10,000 messages with one context, and watch memory with dotnet-counters; then create a scope per message.DbContext as the unit of work, and an explicit transaction inside the execution strategy for an operation that mixes ExecuteUpdateAsync with tracked changes.
namespace Shop.Infrastructure;
using Microsoft.EntityFrameworkCore;
public interface IUnitOfWork
{
Task<int> SaveChangesAsync(CancellationToken cancellationToken = default);
}
public sealed class ShopDbContext(DbContextOptions<ShopDbContext> options) : DbContext(options), IUnitOfWork
{
public DbSet<Order> Orders => Set<Order>();
public DbSet<StockItem> Stock => Set<StockItem>();
public DbSet<AuditEntry> Audit => Set<AuditEntry>();
protected override void OnModelCreating(ModelBuilder modelBuilder) =>
modelBuilder.Entity<StockItem>().HasKey(s => s.Sku); // not named Id, so the key must be configured
}
public sealed class Order
{
public Guid Id { get; init; } = Guid.CreateVersion7();
public required string Sku { get; init; }
public int Quantity { get; init; }
public string Status { get; set; } = "Placed";
}
public sealed class StockItem
{
public required string Sku { get; init; }
public int Available { get; set; }
}
public sealed record AuditEntry(Guid Id, string Action, DateTimeOffset At);
namespace Shop.Orders;
using Microsoft.EntityFrameworkCore;
using Shop.Infrastructure;
public sealed class PlaceOrderHandler(ShopDbContext db, TimeProvider clock)
{
public async Task<Guid> HandleAsync(string sku, int quantity, CancellationToken ct)
{
var strategy = db.Database.CreateExecutionStrategy(); // required when EnableRetryOnFailure is on
return await strategy.ExecuteAsync(async () =>
{
db.ChangeTracker.Clear(); // the block may re-run after a transient failure
await using var tx = await db.Database.BeginTransactionAsync(ct);
// Runs immediately and bypasses the change tracker: only atomic because of tx
var reserved = await db.Stock
.Where(s => s.Sku == sku && s.Available >= quantity)
.ExecuteUpdateAsync(s => s.SetProperty(x => x.Available, x => x.Available - quantity), ct);
if (reserved == 0) throw new InvalidOperationException($"Not enough stock for {sku}.");
var order = new Order { Sku = sku, Quantity = quantity };
db.Orders.Add(order);
db.Audit.Add(new AuditEntry(Guid.CreateVersion7(), $"Order {order.Id} placed", clock.GetUtcNow()));
await db.SaveChangesAsync(ct); // tracked changes in the same transaction
await tx.CommitAsync(ct); // dispose without commit = rollback
return order.Id;
});
}
}
// Program.cs: scoped context, so every repository/handler in a request shares one unit of work
builder.Services.AddDbContext<ShopDbContext>(o =>
o.UseSqlServer(builder.Configuration.GetConnectionString("Shop"),
sql => sql.EnableRetryOnFailure(maxRetryCount: 5)));
builder.Services.AddScoped<IUnitOfWork>(sp => sp.GetRequiredService<ShopDbContext>());
builder.Services.AddSingleton(TimeProvider.System);
builder.Services.AddScoped<PlaceOrderHandler>();
DbContext. Why it is wrong: Each context is a separate unit of work, so changes commit separately and can be half-saved. Instead: Register the context and repositories as scoped so they share one instance per operation.SaveChangesAsync after every change. Why it is wrong: Each call is its own transaction; a later failure leaves earlier changes committed. Instead: Make changes, then save once at the end of the use case.ExecuteUpdateAsync/ExecuteDeleteAsync with SaveChangesAsync and expecting one commit. Why it is wrong: Execute* methods commit immediately on their own and bypass the change tracker. Instead: Wrap both in an explicit transaction.BeginTransactionAsync with EnableRetryOnFailure on, outside an execution strategy. Why it is wrong: EF throws because it can't retry part of a user transaction. Instead: Wrap the whole unit in CreateExecutionStrategy().ExecuteAsync and make it repeatable.DbContext alive for a whole background worker. Why it is wrong: The change tracker grows without bound, data goes stale, and the context isn't thread-safe. Instead: Create a scope (or use IDbContextFactory) per message or batch.UnitOfWork class that manages its own transactions and repositories. Why it is wrong: It duplicates EF Core and often mishandles disposal and retries. Instead: Let DbContext implement a thin IUnitOfWork if you need the abstraction.Most Unit of Work bugs I see aren't about the pattern; they're about boundaries. Either the operation has two contexts (two units of work pretending to be one), or it mixes immediate operations like ExecuteUpdate with tracked changes and assumes they commit together. I keep one scoped context per operation, save once, and reach for explicit transactions only when the operation really spans several commands.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
Implicit SaveChangesAsync |
Most use cases | None | Mixed immediate SQL + tracked changes |
BeginTransactionAsync (+ execution strategy) |
Several saves, Execute*, raw SQL |
Longer locks, repeatable block | Single save |
TransactionScope |
Legacy code with several connections | Async-flow flag, escalation risk | Azure SQL, cross-platform services |
| Outbox | Database + message broker | Relay process, at-least-once delivery | Pure database operations |
I measure with SQL logging (count BEGIN TRANs per request), Application Insights dependency telemetry, and reconciliation queries that look for orphaned rows after failures.
A captive dependency is a service held by a consumer that lives longer than it should. Most often a scoped service (such as DbContext or a current-user service) is injected into a singleton, so it is created once and shared by every request. That leads to cross-user data leaks, "A second operation was started on this context instance", stale tracked entities and ObjectDisposedException.
ValidateScopes throws when a scoped service is resolved from the root or from a singleton. ValidateOnBuild checks every registration when the provider is built. Both are on only in Development by default, so turn them on in tests too.
The fix is either to make the consumer scoped, or to inject IServiceScopeFactory and create a scope per unit of work. A transient captured by a singleton is also captive, and validation won't catch it.
The State pattern makes behaviour depend on the current state and makes transitions explicit, so "ship a cancelled order" is rejected rather than a status field being overwritten.
Three implementations, from lightest:
(state, trigger): a compact, readable transition table; anything not listed is rejected.IOrderState per state): worth it when each state has substantial behaviour of its own.Permit, PermitIf guards, OnEntry actions, CanFire, and graph export, with external state storage so EF Core persists a plain Status column.Invalid transitions return 409 Conflict. Because two requests can both pass the check in memory, add a rowversion concurrency token so the second SaveChanges fails. The trade-off: a library and classes buy guards and visualisation at the cost of indirection; a switch table is often enough.
Last updated 18 Nov 2026.