fix(core): run the outbox handler before dispatching other event handlers - #905
Merged
Merged
Conversation
Proves that the default parallel dispatcher runs OutboxEventHandler concurrently with a user handler that shares the caller's scoped dependency (#812).
…nd scoped handler A user handler that shares the caller's DbContext collides with the EF outbox write under the default parallel dispatcher (#812).
…handlers The outbox handler writes through the caller's scoped services (e.g. the EF DbContext). PublishAsync now invokes it first and on its own, inside the interceptor chain, and passes only the remaining handlers to the configured dispatcher, so the outbox write never runs concurrently with another handler. Failures of all handlers are still collected into one flat AggregateException.
Adds a proposed ADR, XML docs on AddOutbox, AddEntityFrameworkOutbox, ParallelEventDispatcher and IEvent, and README sections covering SequentialEventDispatcher for handlers that share a scoped DbContext and the SaveChangesAsync side effect of the EF outbox.
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #905 +/- ##
==========================================
+ Coverage 96.07% 96.10% +0.03%
==========================================
Files 274 274
Lines 11514 11540 +26
Branches 1072 1076 +4
==========================================
+ Hits 11062 11091 +29
- Misses 232 233 +1
+ Partials 220 216 -4 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
… per-event sequential dispatch
Dispatcher XML docs now state that the outbox handler is never passed to a dispatcher. READMEs and the ParallelEventDispatcher caution show UseEventDispatcherFor<TEvent, SequentialEventDispatcher>() as the per-event option. The ADR applyTo glob now matches OutboxEventHandler{TEvent}.cs.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #812
Summary
The default
ParallelEventDispatcherran the framework'sOutboxEventHandler<TEvent>at the same time as user handlers resolved from the caller's scope. With the EF outbox, both used the same scopedDbContext.PublishAsyncthen failed intermittently with "A second operation was started on this context instance".With this change,
PulseMediatoralways runs the outbox handler first and on its own. Only the remaining handlers go to the configured dispatcher.Changes
PulseMediator.ExecuteAsyncsplits the resolved handlers into outbox handlers and all other handlers.InvokeHandlerAsync. Only the remaining handlers go to the resolved dispatcher (keyed, global or the parallel default). The dispatcher is skipped when no handlers remain.AggregateException.ParallelEventDispatcherstays the default and stays available as an opt-in.PublishAsyncremarksAddOutboxAddEntityFrameworkOutboxParallelEventDispatchercautionIEventIEventDispatcher,SequentialEventDispatcher,PrioritizedEventDispatcherandRateLimitedEventDispatcher: the outbox handler is never passed to a dispatcher, and registration or priority order applies only to the remaining handlersNetEvolve.Pulse("Outbox and Handlers Sharing the Caller's Scope") andNetEvolve.Pulse.EntityFramework("Event Handlers Sharing the DbContext"). They cover:UseEventDispatcherFor<MyEvent, SequentialEventDispatcher>()workaround for several user handlers on oneDbContext, withUseDefaultEventDispatcher<SequentialEventDispatcher>()as the app-wide alternativeSaveChangesAsync-on-shared-context effectdecisions/2026-09-29-outbox-handler-runs-before-event-dispatcher.md(state: proposed). It records why the fix runs the outbox first and does not make the sequential dispatcher the default. ItsapplyTousesOutboxEventHandler*.cs, because{TEvent}in a glob is brace alternation and would not match the file.Bug hunt
PulseMediatorOutboxDispatchTests.PublishAsync_WithOutboxAndScopedHandler_DefaultDispatcher_NeverUsesSharedDependencyConcurrentlyDbContextthrows EF Core's concurrent-useInvalidOperationException*EntityFrameworkOutboxSharedContextTests.PublishAsync_WithSharedDbContextHandler_PersistsBoth(asserts the outbox rows and the handler rows are both persisted)PublishAsync_WithOutboxAndSingleHandler_PassesOnlyUserHandlerToDispatcherPublishAsync_WithOnlyOutboxHandler_StoresEventWithoutDispatcherPublishAsync_WithFailingOutbox_StillRunsOtherHandlersAndThrowsFlatAggregatePublishAsync_WithSuppressingInterceptor_DoesNotStoreOutboxMessageEntityFrameworkOutboxRepository.AddAsynccallsSaveChangesAsyncon the shared context and flushes the caller's pending changesThe existing
ParallelEventDispatcherTestsstill cover the opt-in parallel dispatcher for independent handlers and its single-handler fast path.Impact
SequentialEventDispatcherfollowed registration order. Custom dispatchers (for example rate-limited or prioritized) no longer receive the outbox handler.DbContextstill needSequentialEventDispatcher, per event viaUseEventDispatcherFor<TEvent, SequentialEventDispatcher>()or for all events. This is now documented.Test evidence
dotnet build Pulse.slnx -c Release: 0 errors, 0 warnings.csharpier check .is clean.origin/mainand the review follow-up (docs only): build 0 errors, 0 warnings. Unit tests (net8.0,net9.0,net10.0): 7257 total, 7257 passed.net10.0):*EntityFrameworkOutboxSharedContextTestson SQLite, InMemory, SqlServer, PostgreSql and MySql: red before the fix, 5/5 green after it.