A working EF Core 10 implementation of domain events: an aggregate base class, a SaveChangesInterceptor that collects and dispatches events before commit, transaction and execution-strategy handling, and the failure modes such as recursion, lost events and re-entrancy.
I give aggregates a base class with a private list of domain events, raised inside behaviour methods. A SaveChangesInterceptor overrides SavingChangesAsync: it collects events from ChangeTracker.Entries<AggregateRoot>(), clears them, and dispatches them to handlers resolved from the current DI scope. Because this runs before EF Core writes, any changes handlers make to the same DbContext are saved in the same SaveChanges call and transaction. I loop until no new events appear, with a depth limit.
Anything that must leave the process goes to an outbox row, not a broker call. The trade-off: in-transaction handlers give atomicity but make the save slower and the transaction bigger, so they must stay local and fast.
"I start with the aggregate. It inherits an
AggregateRootbase class that holds a privateList<IDomainEvent>and exposes it asIReadOnlyList. Behaviour methods likeOrder.Place()change state and callRaise(new OrderPlaced(...)); nothing outside the aggregate can add events. Then I write aSaveChangesInterceptorand overrideSavingChangesAsync. That hook runs after EF Core has calledDetectChangesbut before it builds and executes any SQL, so it's the right moment: I pull every tracked aggregate with pending events, copy the events, clear them on the aggregates, and dispatch each to its handlers.Handlers are resolved from the same scope as the
DbContext, so a handler that adds loyalty points or writes an outbox row modifies the same context. When my interceptor returns, EF Core runsDetectChangesagain as part of saving, and all those changes go into one batch inside the implicit transaction. If a handler throws, nothing is saved. Handlers can raise further events, so I loop until there are none, with a limit of, say, five passes so a cycle fails loudly instead of hanging.There are traps. If I don't clear events before dispatching, a retry from
EnableRetryOnFailuredispatches them twice. If I register the interceptor as a singleton but it needs scoped handlers, I get a captive dependency, so I add it with theAddDbContext((sp, options) => ...)overload and resolve it per scope. And I never call an external API from a handler inside the transaction; that goes to the outbox.The mistake I see is dispatching events after
SaveChangesreturns and assuming they are part of the same unit of work. They aren't, and a crash in between silently loses the side effect."
| Hook | Runs | Handler changes saved? | Use for |
|---|---|---|---|
SavingChangesAsync (interceptor) |
Before SQL, inside the save | Yes, same transaction | Domain event handlers that must be atomic |
Override SaveChangesAsync before base call |
Same as above | Yes | Same, when you prefer no interceptor |
SavedChangesAsync (interceptor) |
After commit (implicit tx) | Needs another save | Post-commit, non-critical side effects |
| Outbox relay | Later, background | N/A | Integration events to other services |
| Approach | Pros | Cons |
|---|---|---|
| Interceptor | Reusable, testable, keeps DbContext clean | Must get DI scoping right |
| Override in DbContext | Simple, obvious | DbContext needs a dispatcher dependency |
In a [claims] service, moving loyalty and audit side effects into in-transaction domain event handlers removed a class of partial failures that had produced [~15] inconsistent records a month. Average SaveChanges time rose from 18 ms to 22 ms, which we accepted; a slow PDF-generation handler was moved to the outbox after it pushed p99 above 400 ms.
Checks that the candidate can implement domain events correctly with EF Core, understands the save pipeline and transaction, and anticipates DI scoping, retries and recursion.
Green flags
SavingChangesAsync (or pre-base override) and explains why it is atomicRed flags
SaveChanges or HTTP inside handlersSaveChangesAsync()
-> DetectChanges
-> interceptors: SavingChangesAsync <-- dispatch domain events here
-> DetectChanges again (picks up handler changes)
-> begin implicit transaction (if none)
-> batched INSERT / UPDATE / DELETE
-> commit
-> interceptors: SavedChangesAsync / SaveChangesFailedAsync
EF Core runs DetectChanges automatically in SaveChanges unless AutoDetectChangesEnabled is off, so entities added or modified by handlers are included. Check the behaviour for your version with a test: if your handlers add new entities after detection, calling context.ChangeTracker.DetectChanges() at the end of the interceptor is a cheap safety net.
ChangeTracker.Entries<AggregateRoot>()
.Select(e => e.Entity)
.Where(a => a.DomainEvents.Count > 0)
Copy to a list, then call ClearDomainEvents() on each aggregate before dispatching. Clearing first means a retry (from an execution strategy) or a second SaveChanges does not dispatch the same events again.
The interceptor needs IServiceProvider for the current scope. Options:
AddDbContext((sp, o) => o.AddInterceptors(sp.GetRequiredService<DomainEventInterceptor>())).AddDbContextPool, the options are built once, so a scoped interceptor is captured by the pool. Use IDbContextFactory or resolve handlers through context.GetService<IServiceProvider>() carefully, or avoid pooling for this context.Handlers may raise events on other aggregates. Loop:
pass = 0
while (events = collect()).Any():
if ++pass > 5: throw
dispatch(events)
Dispatch in the order events were raised. Do not rely on handler order for the same event; if order matters, it's one handler.
The implicit transaction wraps the whole save. If you start an explicit transaction with BeginTransactionAsync, the save joins it. With EnableRetryOnFailure, wrap user-initiated transactions in Database.CreateExecutionStrategy().ExecuteAsync(...). Because events are cleared before dispatch, a retried operation must re-run the aggregate behaviour, which the execution strategy does when you put the whole operation inside its delegate.
No HTTP calls, no broker sends, no SaveChanges calls of their own (re-entrancy into the same context throws or nests saves). Write an outbox row instead.
LogTo).EnableRetryOnFailure, inject a transient failure with an interceptor, and check events are not dispatched twice.SaveChanges time with and without handlers using BenchmarkDotNet.Aggregate base class, an interceptor that dispatches before the SQL runs, and the registration that keeps handlers in the request scope.
namespace Ordering.Domain;
public interface IDomainEvent;
public abstract class AggregateRoot
{
private readonly List<IDomainEvent> _domainEvents = [];
public IReadOnlyList<IDomainEvent> DomainEvents => _domainEvents;
protected void Raise(IDomainEvent e) => _domainEvents.Add(e);
public void ClearDomainEvents() => _domainEvents.Clear();
}
public sealed record OrderPlaced(Guid OrderId, decimal Total) : IDomainEvent;
public sealed class Order : AggregateRoot
{
private Order() { }
public Guid Id { get; private set; }
public decimal Total { get; private set; }
public bool IsPlaced { get; private set; }
public static Order Create(decimal total) => new() { Id = Guid.NewGuid(), Total = total };
public void Place()
{
if (IsPlaced) throw new InvalidOperationException("Order already placed.");
IsPlaced = true;
Raise(new OrderPlaced(Id, Total));
}
}
namespace Ordering.Infrastructure;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.DependencyInjection;
using Ordering.Domain;
public interface IDomainEventHandler<in T> where T : IDomainEvent
{
Task HandleAsync(T domainEvent, CancellationToken ct);
}
// Scoped: resolves handlers from the same scope as the DbContext.
public sealed class DomainEventInterceptor(IServiceProvider services) : SaveChangesInterceptor
{
private const int MaxPasses = 5;
public override async ValueTask<InterceptionResult<int>> SavingChangesAsync(
DbContextEventData eventData, InterceptionResult<int> result, CancellationToken ct = default)
{
if (eventData.Context is not { } db) return result;
for (var pass = 1; ; pass++)
{
var aggregates = db.ChangeTracker.Entries<AggregateRoot>()
.Select(e => e.Entity)
.Where(a => a.DomainEvents.Count > 0)
.ToList();
if (aggregates.Count == 0) break;
if (pass > MaxPasses)
throw new InvalidOperationException("Domain event dispatch exceeded the maximum depth; check for cycles.");
var events = aggregates.SelectMany(a => a.DomainEvents).ToList();
aggregates.ForEach(a => a.ClearDomainEvents()); // clear first: no double dispatch on retry
foreach (var domainEvent in events)
await DispatchAsync(domainEvent, ct);
}
db.ChangeTracker.DetectChanges(); // pick up entities handlers added
return result;
}
private async Task DispatchAsync(IDomainEvent domainEvent, CancellationToken ct)
{
var handlerType = typeof(IDomainEventHandler<>).MakeGenericType(domainEvent.GetType());
foreach (dynamic handler in services.GetServices(handlerType))
await handler.HandleAsync((dynamic)domainEvent, ct);
}
}
// Program.cs
builder.Services.AddScoped<DomainEventInterceptor>();
builder.Services.AddScoped<IDomainEventHandler<OrderPlaced>, AwardLoyaltyPoints>();
builder.Services.AddScoped<IDomainEventHandler<OrderPlaced>, WriteOrderPlacedToOutbox>();
// The (sp, options) overload resolves the scoped interceptor per DbContext instance.
builder.Services.AddDbContext<OrderingDbContext>((sp, options) => options
.UseSqlServer(builder.Configuration.GetConnectionString("Ordering"),
sql => sql.EnableRetryOnFailure())
.AddInterceptors(sp.GetRequiredService<DomainEventInterceptor>()));
The dynamic dispatch keeps the sample short; in production I'd cache a compiled delegate per event type (or use a source-generated dispatcher) to avoid reflection cost and stay trimming-friendly.
SaveChanges returns. Why it is wrong: handler changes need a second save and a crash in between loses them. Instead: dispatch in SavingChangesAsync so they join the same transaction.SaveChanges dispatch them again. Instead: copy, clear, then dispatch.IServiceProvider, or one captured by AddDbContextPool). Why it is wrong: the singleton itself is fine, but the scoped handlers it resolves become captive dependencies with a different DbContext from the one being saved, so their changes are never persisted in this transaction. Instead: make the interceptor scoped and add it with the (sp, options) overload, or have a singleton interceptor resolve handlers from the saving context's own scope.SaveChanges inside a handler. Why it is wrong: re-entrant saves on the same context fail or split the transaction. Instead: only modify the context; the outer save persists everything.Raise() only from behaviour methods.I treat the interceptor as infrastructure plumbing that the domain never sees: the domain only knows Raise(). The design question is which handlers belong in the transaction. My rule is: in-transaction handlers only touch the same database and finish in milliseconds; everything else becomes an outbox message, even inside a modular monolith. That keeps the transaction small and the failure modes understandable.
Domain events are not free. Each one adds indirection (a reader can't see from Order.Place() what happens next), reflection or generated dispatch cost per event, and a bigger SaveChanges with more rows and longer lock duration. In the service above, average save time went from 18 ms to 22 ms, which was fine; but on a hot path doing thousands of saves a second, I'd measure before adding handlers and might prefer an explicit call. If a use case has one follow-on step, an explicit call in the handler is clearer. Domain events pay off when several independent reactions hang off one fact, or when the aggregate shouldn't know who cares. Outbox-backed reactions add another trade-off: they're eventually consistent, so the UI and other modules must tolerate a short lag.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Hand-rolled interceptor | Small to medium codebase, full control | ~100 lines to own and test | You already use Wolverine/MassTransit outbox |
| Library (Wolverine, MassTransit EF outbox) | Many events, messaging already in place | Dependency, learning curve | Single simple service |
| Explicit calls in the use case | One or two follow-on steps, hot paths | Coupling in the handler | Many independent reactions |
I'd measure SaveChanges duration (EF Core metrics or Application Insights dependency timing) before and after, and alert if p99 grows past the budget.
A domain event records something meaningful that happened inside one bounded context, such as OrderPlaced. It is raised by an aggregate, handled in-process by other parts of the same model, and uses domain types freely. An integration event is a published contract for other services or modules: serialised, versioned and owned by the publisher.
SaveChanges), so their side effects commit or roll back together.The trade-off: domain events give you strong consistency in one context; integration events give you decoupling at the cost of eventual consistency and at-least-once delivery.
SaveChanges runs a pipeline:
DetectChanges: compares every tracked entity with its original-values snapshot and marks changed properties Modified (skipped if AutoDetectChangesEnabled is false, so you must call it yourself).MaxBatchSize is 42).INSERT ... OUTPUT INSERTED.[Id] returns identity keys and UPDATE ... OUTPUT INSERTED.[RowVersion] returns new row versions; EF Core replaces temporary keys, propagates them to foreign keys, then marks everything Unchanged.The trade-off: one call gives atomicity and few round trips, but its cost grows with every tracked entity.
The dual-write problem: an order is saved in SQL Server and an OrderPlaced event is sent to Service Bus. Those are two systems with no shared transaction. If the publish fails after the commit, the event is lost. If you publish first and the commit fails, consumers act on an order that doesn't exist.
The outbox fixes this by writing the event as a row in an OutboxMessages table in the same EF Core transaction as the order. A relay (a BackgroundService polling with UPDLOCK, READPAST) publishes unprocessed rows and marks them ProcessedAt.
A crash between publish and mark means the row is sent again, so delivery is at-least-once. Consumers must be idempotent (an inbox), helped by setting MessageId to the outbox id for Service Bus duplicate detection. The trade-off is guaranteed publication against extra writes, latency, cleanup and a relay to monitor.
These are two bugs with different causes, so I quantify each with reconciliation queries first.
Task.Run killed on deploy, or a swallowed ServiceBusException).MessageId each time, which defeats duplicate detection, plus peek-lock redelivery after lock expiry on a consumer that isn't idempotent.Fix: an outbox. A SaveChanges interceptor writes domain events to OutboxMessages in the same transaction, and a relay publishes with MessageId = outbox id. Add an inbox on each consumer: (MessageId, Consumer) PK, insert first, treat 2627/2601 as done.
Roll out the inbox first, because the outbox makes delivery at-least-once. Then backfill missing events, refund double charges, and keep daily reconciliation. The trade-off is extra tables and a relay against guaranteed, deduplicated delivery.
How to tell it (STAR)
**S:** After we enabled SQL retries, [some] customers got duplicate renewal letters and double loyalty points. **T:** I [owned the domain event infrastructure] and needed to stop the duplicates. **A:** I matched the duplicates to transient SQL errors in Application Insights, reproduced it with a failing interceptor in a test, and found events were cleared too late. I changed the order to copy-clear-dispatch, wrapped the use case in an execution strategy, and moved letters to the outbox. **R:** Duplicates went from [~0.5%] of renewals to zero, and the new test has caught [one] regression since.
Last updated 23 Nov 2026.