Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ namespace Mocha.EntityFrameworkCore;

/// <summary>
/// Mediator middleware that wraps command handling in a database transaction.
/// Commits on success and rolls back on failure.
/// Commits on success and rolls back on failure. Handlers are responsible for
/// calling <see cref="DbContext.SaveChangesAsync(CancellationToken)"/> themselves.
/// Queries and notifications are excluded by default but can be opted in via
/// <see cref="MediatorEntityFrameworkOptions.ShouldCreateTransaction"/>.
/// </summary>
Expand Down Expand Up @@ -37,7 +38,6 @@ await strategy.ExecuteAsync(async ct =>
{
await next(context);

await dbContext.SaveChangesAsync(ct);
await transaction.CommitAsync(ct);
}
catch
Expand All @@ -57,7 +57,6 @@ await strategy.ExecuteAsync(async ct =>
{
await next(context);

await dbContext.SaveChangesAsync(context.CancellationToken);
await transaction.CommitAsync(context.CancellationToken);
}
catch
Expand Down
8 changes: 3 additions & 5 deletions website/src/docs/mocha/v1/mediator/pipeline-and-middleware.md
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,6 @@ public static class TransactionMiddleware
try
{
await next(ctx);
await db.SaveChangesAsync(ctx.CancellationToken);
await tx.CommitAsync(ctx.CancellationToken);
}
catch
Expand Down Expand Up @@ -462,11 +461,10 @@ The middleware (key: `"EntityFrameworkTransaction"`):
1. Checks at compile time whether the pipeline is for a command. Queries and notifications are excluded by default - the middleware is not present in their pipelines at all.
2. Begins a database transaction
3. Calls the next middleware or handler
4. Calls `SaveChangesAsync` on success
5. Commits the transaction
6. Rolls back on any exception
4. Commits the transaction on success
5. Rolls back on any exception

Your command handlers do not need to call `SaveChangesAsync` or manage transactions - the middleware handles both.
Your command handlers are responsible for calling `SaveChangesAsync` to persist their changes. The middleware handles the transaction lifecycle - your handlers do not need to call `BeginTransactionAsync`, `CommitAsync`, or `RollbackAsync`.

## Customizing transaction scope

Expand Down
Loading