With MediatR and EF Core, how would you write a transaction behaviour for commands, and what breaks with nested Send calls, notifications and a retrying execution strategy?
answer
- marker-interface constraint: commands only
- BeginTransactionAsync, await next, CommitAsync
- nested Send: connection already in a transaction
- Publish inside runs before the commit
- execution strategy retries the whole delegate
basics
~20 sConstrain it to a command marker, begin a transaction on the request's DbContext, await next, commit; disposal rolls back on failure. Guard nested Send with CurrentTransaction, defer side effects until after commit, and run it inside the execution strategy.
solid answer
~40 sA `TransactionBehavior<TRequest, TResponse>` constrained `where TRequest : ICommand` (your own marker, so queries skip it) injects the scoped `DbContext`, calls `Database.BeginTransactionAsync`, awaits `next`, then `CommitAsync`; an exception skips the commit and disposing the transaction rolls it back. Three things break it. A handler that sends another command re-enters the pipeline with the same scoped context, and the inner `BeginTransactionAsync` throws `InvalidOperationException` ("The connection is already in a transaction..."), so check `Database.CurrentTransaction` and just call `next`. A notification published inside the handler runs before the commit, so an email can go out for a payment that is then rolled back; publish after commit or use an outbox. With a retrying execution strategy, EF Core rejects user-initiated transactions unless the block runs inside `CreateExecutionStrategy().ExecuteAsync`, and a retry re-runs `next`, handler included.
code
csharp · 3 linespublic record RecordRentPayment(Guid LeaseId, decimal Amount) : IRequest<PaymentReceipt>, ICommand;
public record ArchiveProperty(Guid PropertyId) : IRequest, ICommand;
public record GetLeaseSummary(Guid LeaseId) : IRequest<LeaseSummary>; // query: no transactiongo deeper
Recall the shape of a transaction behaviour: begin a transaction, call next, commit, and let disposal roll back when the handler throws.
Explain why the behaviour is constrained to a command marker, how it shares the handler's scoped DbContext, and why it is registered innermost.
Diagnose the failure modes: nested Send throwing on BeginTransactionAsync, side effects escaping a rolled-back transaction, and retries re-running the handler under an execution strategy.
Decide where transaction boundaries live, per command, per handler or per unit of work, and how events leave the transaction reliably, for example through an outbox.
## The basic shape A transaction behaviour makes each command's database work atomic without every handler opening its own transaction. In the property-management API, `RecordRentPayment` inserts a payment, updates the lease balance and writes an audit row; either all three commit or none do. ```csharp public interface ICommand { } public sealed class TransactionBehavior<TRequest, TResponse>(PropertyDbContext db) : IPipelineBehavior<TRequest, TResponse> where TRequest : ICommand { public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken) { if (db.Database.CurrentTransaction is not null) return await next(cancellationToken); // nested Send joins the outer one var strategy = db.Database.CreateExecutionStrategy(); return await strategy.ExecuteAsync(async () => { await using var tx = await db.Database.BeginTransactionAsync(cancellationToken); var response = await next(cancellationToken); await tx.CommitAsync(cancellationToken); return response; }); } } ``` - **`where TRequest : ICommand`**: a non-generic marker of your own, implemented next to `IRequest<T>` or `IRequest` (`record RecordRentPayment(...) : IRequest<PaymentReceipt>, ICommand`). Queries do not implement it, so the container skips the behaviour for them. Because the constraint does not mention `TResponse`, it works for void commands too. - **Same `DbContext` as the handler**: behaviours and handlers resolved for one `Send` from a request-scoped mediator share the scoped context, so the handler's `SaveChangesAsync` runs inside the transaction. - **Rollback by disposal**: if `next` throws, `CommitAsync` is skipped and disposing the `IDbContextTransaction` rolls back. ## Nested `Send` When `RenewLeaseHandler` sends `RecordRentPayment`, the inner `Send` passes through the whole pipeline again. The inner `TransactionBehavior` gets the same scoped context, which already has a transaction, and EF Core's relational provider throws `InvalidOperationException`: "The connection is already in a transaction and cannot participate in another transaction." Options: 1. check `Database.CurrentTransaction` and call `next` directly, joining the outer transaction (as above); 2. stop commands from sending commands, and extract the shared logic into a service both handlers call. ## Notifications inside the transaction If `RecordRentPaymentHandler` calls `Publish(new RentPaymentRecorded(...))`, every notification handler runs **inline, before the behaviour reaches `CommitAsync`**: - database writes those handlers make through the same context are part of the transaction and roll back with it; - an email, an HTTP call or a message sent to a broker **does not** roll back. If the commit then fails, the tenant has a receipt for a payment that never happened. Fixes: have the handler collect domain events and publish them **after** `CommitAsync` (for example from the transaction behaviour itself), or write them to an outbox table inside the transaction and let a background process deliver them. ## Retrying execution strategies A provider configured with a retrying execution strategy (connection resiliency) refuses a transaction opened outside the strategy: EF Core throws `InvalidOperationException` saying the configured execution strategy does not support user-initiated transactions and to run the operations through the strategy. Wrapping begin, `next` and commit in `CreateExecutionStrategy().ExecuteAsync(...)` fixes that, with consequences: - On a transient failure the **whole delegate runs again**: inner behaviours and the handler execute a second time. - Entities the failed attempt left in the change tracker are still tracked; the handler must cope with re-running, for example by reloading state, or the behaviour can call `ChangeTracker.Clear()` before each attempt. - Non-database side effects inside the delegate repeat on every retry, one more reason to keep them after the commit. ## Where `SaveChangesAsync` belongs Two styles work, and mixing them causes confusion: - **Handler saves.** Each handler calls `SaveChangesAsync` itself; the behaviour only brackets those saves with a transaction. Handlers stay explicit, and a handler that saves twice still commits atomically. - **Behaviour saves.** Handlers only change tracked entities; the behaviour calls `SaveChangesAsync` once after `next` returns and before `CommitAsync`, acting as a unit of work. Handlers get shorter, but a handler that needs a generated key mid-way must save early anyway. Pick one convention per codebase. A query sent from inside a command handler shares the context and the transaction, so it sees changes the command already saved but has not committed, which is usually what you want. ## Placement Register the transaction behaviour **innermost**, after logging and validation, so invalid commands never open a transaction and the transaction is held for as short a time as possible. MediatR's post-processors, which `AddMediatR` places outside your behaviours, run after the commit.
- Why does BeginTransactionAsync throw when one MediatR command handler sends another command?The nested `Send` re-enters the pipeline, and the inner `TransactionBehavior` resolves the same scoped `DbContext`, which already has an open transaction. EF Core's relational provider throws `InvalidOperationException` ("The connection is already in a transaction and cannot participate in another transaction."). Check `Database.CurrentTransaction` and just call `next`, or stop commands from sending commands.
- A handler publishes RentPaymentRecorded inside the transaction, and the commit then fails. What happened to the notification's effects?They already ran: `Publish` executes notification handlers inline, before the behaviour reaches `CommitAsync`. Database writes they made through the same context roll back with the transaction, but an email or HTTP call does not, so the tenant got a receipt for a rolled-back payment. Publish after the commit, or write the event to an outbox inside the transaction.
- What changes when the DbContext uses a retrying execution strategy?EF Core refuses a user-initiated transaction opened outside the strategy, so begin, `next` and commit must run inside `Database.CreateExecutionStrategy().ExecuteAsync(...)`. A transient failure then re-runs the whole delegate, inner behaviours and handler included, on the same context, so handlers must tolerate re-execution and stale tracked entities may need `ChangeTracker.Clear()`.
- MediatR wraps every Send in a database transaction by default.
- A nested Send automatically joins the outer EF Core transaction.
- Notifications published inside the handler run after the commit.
- The execution strategy retries only the failed SQL statement, not the handler.
- A rolled-back transaction also undoes emails sent by notification handlers.