Skip to content

[Mocha] Add DbContext.Outbox for atomic SaveChanges publishes - #11018

Draft
tobias-tengler wants to merge 31 commits into
mainfrom
tte/mocha-dbcontext-outbox
Draft

tobias-tengler wants to merge 31 commits into
mainfrom
tte/mocha-dbcontext-outbox

Conversation

@tobias-tengler

@tobias-tengler tobias-tengler commented Nov 21, 2026 •

Copy link
Copy Markdown
Member
  • dbContext.Outbox(bus) returns a DbContextOutbox whose PublishAsync and SendAsync stage a message that the next SaveChanges writes in the same transaction as the entity changes.
  • A message with a ScheduledTime is staged the same way, and the outbox processor hands it to the scheduler after commit.
  • A save or commit that writes staged messages wakes the outbox processor.
  • With AutoTransactionBehavior.Never, a save that would write staged messages outside a transaction is rejected.
  • A publish or send that throws stages nothing.
  • SkipOutbox() has no effect on a message published or sent through the outbox.
  • The outbox accepts only the IMessageBus that Mocha registers in the service provider of the context.
  • The outbox processor claims a message that was never attempted regardless of its created_at.
  • The OutboxMessage constructor takes the creation time as a third argument, and OutboxMessage.Envelope gets a value converter. The table is unchanged.
  • The source generator handles dbContext.Outbox(bus) call sites like IMessageBus call sites.
  • Requires .NET 9 or later. On .NET 8 the method throws NotSupportedException.

@github-actions

github-actions Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Patch coverage

99.1% of changed lines covered (329/332)

File Covered Changed Patch %
src/Mocha/src/Mocha.EntityFrameworkCore/ThrowHelper.cs 21 23 91.3% 🟡
…/Outbox/PostgresDbContextOutbox.cs 68 69 98.6% 🟡
…/Mocha.Analyzers/Inspectors/CallSiteMessageTypeInspector.cs 4 4 100.0% 🟢
src/Mocha/src/Mocha.Analyzers/KnownTypeSymbols.cs 1 1 100.0% 🟢
…/Outbox/OutboxAtomicSaveInterceptor.cs 19 19 100.0% 🟢
…/Mocha.EntityFrameworkCore.Postgres/Outbox/OutboxMessage.cs 2 2 100.0% 🟢
…/Mocha.EntityFrameworkCore.Postgres/Outbox/OutboxProcessor.cs 8 8 100.0% 🟢
…/Outbox/OutboxServiceCollectionExtensions.cs 7 7 100.0% 🟢
…/Outbox/PostgresMessageOutbox.cs 1 1 100.0% 🟢
…/Outbox/PostgresMessageOutboxQueries.cs 1 1 100.0% 🟢
…/Outbox/PostgresOutboxMessageEntityConfiguration.cs 7 7 100.0% 🟢
…/src/Mocha.EntityFrameworkCore.Postgres/Outbox/ThrowHelper.cs 11 11 100.0% 🟢
…/src/Mocha.EntityFrameworkCore/Outbox/DbContextOutbox.cs 55 55 100.0% 🟢
…/Outbox/DbContextOutboxExtensions.cs 19 19 100.0% 🟢
…/src/Mocha.EntityFrameworkCore/Outbox/DbContextOutboxState.cs 6 6 100.0% 🟢
…/OutboxEntityFrameworkCorePersistenceBuilderExtensions.cs 2 2 100.0% 🟢
…/Outbox/OutboxSaveChangesInterceptor.cs 15 15 100.0% 🟢
src/Mocha/src/Mocha.Outbox/DispatchOutboxMiddleware.cs 9 9 100.0% 🟢
src/Mocha/src/Mocha/Middlewares/DefaultMessageBus.cs 62 62 100.0% 🟢
…/Mocha/src/Mocha/Scheduling/DispatchSchedulingMiddleware.cs 11 11 100.0% 🟢
Uncovered changed lines (JSON)
{
  "sha": "0e013477ede9b705b62773ed9bf43ded999d360b",
  "files": [
    { "path": "src/Mocha/src/Mocha.EntityFrameworkCore/ThrowHelper.cs", "ranges": [[52, 53]] },
    { "path": "src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/PostgresDbContextOutbox.cs", "ranges": [[115, 115]] }
  ]
}

Project coverage: 60.2% (331204/550599 lines)

@tobias-tengler
tobias-tengler force-pushed the tte/mocha-dbcontext-outbox branch 2 times, most recently from 753b1d3 to 75a4486 Compare November 21, 2026 19:54
@tobias-tengler
tobias-tengler force-pushed the tte/mocha-ef-outbox-contexts branch 2 times, most recently from cccf8c5 to c4b0ad1 Compare November 22, 2026 11:07
@tobias-tengler
tobias-tengler force-pushed the tte/mocha-dbcontext-outbox branch from 75a4486 to 0372218 Compare November 22, 2026 11:07
…s delivered

A message that the outbox or a scheduler stored was delivered by running the dispatch pipeline a second time with SkipOutbox() and SkipScheduler() set. Bus middleware registered before the outbox therefore ran twice, and transport and endpoint middleware, such as the RabbitMQ routing key extractor, ran only at delivery. The pipeline now runs once, in the order instrumentation, transport and application middleware, serialization, scheduling, outbox, so everything is applied before the message is stored. The outbox processor and the scheduler workers send the stored envelope straight to the transport and record a failed send on their own span. UseOutboxCore() adds the outbox middleware as a fixed stage after scheduling, so anchors to it no longer depend on registration order. SkipScheduler() and SchedulingMiddlewareFeature are removed, and the scheduling and outbox middleware throw when a dispatch reaches them without an envelope.
…ion tests

A test stores a published message in the outbox, delivers the stored envelope through DispatchInternalAsync and checks that the handler receives it while the outbox keeps the one stored message.
…messages

The tests check that changes dispatch middleware makes before next end up in the stored message, that the message is serialized before middleware unwinds, that middleware can anchor to every built-in stage, that middleware anchored after serialization runs for a stored message, that a cancellation after the dispatch completes it, and that scheduling returns the requested time when middleware changes it after next.
…ey set by dispatch middleware

Application middleware now runs before the RabbitMQ routing key extractor, so it can set the routing key header itself, but the extractor overwrote the header with the key extracted from the message. It now keeps a header that is already set, as the Azure Service Bus property middleware does. Tests cover that both extractors see a message that middleware replaced or changed, that middleware anchored after serialization reads the extracted values, and that Service Bus properties survive an envelope that was stored and read back.
…ransport

The scheduler worker was the only code in the in-memory transport that used Mocha.Outbox, for SkipOutbox(). It sends stored envelopes directly now, so the project reference is removed. An application that got Mocha.Outbox only through the in-memory transport has to reference it itself.
…ed messages

The middleware page shows the new dispatch order, says that middleware without an anchor runs before serialization, lists the keys of the built-in middleware and explains how anchors are resolved. The reliability, scheduling, observability and transport pages say that dispatch middleware runs when a message is stored and that the outbox processor and the scheduler send the stored envelope directly. The skip-the-outbox section shows a middleware anchored before OutboxDispatchMiddlewares.Outbox. The dispatch registration sample no longer calls an AddMessageBus overload that does not exist.
The migration guide covers the removal of SkipScheduler(), the in-memory transport no longer referencing Mocha.Outbox, stored messages bypassing middleware during delivery, including rows written by 16.7, and the new position of middleware registered without an anchor.
… registered last

UseTransaction() looked up the DbContext type in a bus feature that every AddEntityFramework<TContext>() call overwrote. With two contexts, the consumer transaction was opened on the context registered last, also when UseTransaction() was configured on the first. The middleware now gets the context type of the builder it is configured on. The builder extensions, the execution strategy and the transaction middleware move from MessageBusHostBuilderExtensions.cs into files of their own.
…t use Mocha

The messaging options extension captured the application service provider and made it part of EF Core's service provider cache key, and the outbox and scheduling interceptors were created with the signals of that provider. Every host in a process therefore built its own EF Core internal service provider and model. The extension now carries the outbox signal, the scheduler signal and the clock of its application, and the interceptors read them from the context they are called for, so contexts of several hosts share one internal provider and still signal their own application. ConfigureEntityFrameworkServices and MessagingDbContextOptions become internal, because the delegate can no longer capture application services.
…t signaled about

An idle outbox processor waited for its signal without a timeout. A row committed without a signal, for example in a transaction that is committed outside EF Core or by another process, stayed in the outbox until something else woke the processor. The processor now also wakes after PostgresOutboxOptions.PollingInterval, ten seconds by default, and an interval that is not positive is rejected. It logs that it is sleeping only when it waits for a message that is due before the next check.
…Contexts use it

UsePostgresOutbox() registered the processor and its worker as plain singletons, so with two contexts the host ran only the processor of the context registered last and the rows of the other context were never sent. Each context now gets its own processor, registered as a keyed singleton with the context type as key, and its own worker. Calling UsePostgresOutbox() or UseOutboxCore() again for the same context registers nothing twice and still applies the configure delegate. IMessageBus publishes keep using the outbox of the first context, and the exception for a missing transaction now says so.
…lve it

When the DbContext of an outbox was not registered as a service, for example with AddPooledDbContextFactory before EF Core 10, resolving the processor failed with the container's missing service error. The outbox now throws an InvalidOperationException that names the context and the registrations that make it resolvable.
… its connection did not enlist

PostgresMessageOutbox accepted a publish as transactional whenever Transaction.Current was set. With Enlist=false in the connection string the connection does not join the ambient transaction, so the outbox row was written outside it and stayed when the scope rolled back. The check now asks the transaction manager of the context. A publish on a connection that has not joined throws the transaction-required exception, and a transaction enlisted through Database.EnlistTransaction without an ambient one is accepted.
…upgrade notes

The reliability page says when the outbox processor is woken at once and when it finds a message at its next check, how to configure the polling interval, and which context IMessageBus publishes use when several contexts have an outbox. The migration guide covers the keyed outbox processors, the internal EF Core registration types, UseTransaction() using its own context, the idle check, and EF Core services being shared across hosts.
…nsion

PostgresMessageOutbox carried the lookup of a DbContext by its runtime type as an internal static, and the outbox registration called into the store class for it. The lookup is now GetRequiredDbContext on IServiceProvider in Mocha.EntityFrameworkCore, the project that owns the context type of the builder. Its exception moves to that project's ThrowHelper as DbContextNotRegistered and keeps its message.
The guide listed ConfigureEntityFrameworkServices and MessagingDbContextOptions becoming internal, and PostgresOutboxProcessor being registered as a keyed singleton per DbContext type. Both entries are removed from the API breaking changes.
…t wrote no outbox message

Every SaveChanges and every transaction commit on an outbox context signaled the outbox processor, so the processor queried the outbox table after each of them, whether or not a message was written. The outbox now marks its context when it writes a message inside a database transaction, and the commit interceptor signals only when the mark is set. OutboxSaveChangesInterceptor is removed, so a save no longer signals. An OutboxMessage entity that is added through the change tracker is found when the processor next checks the database.
All outbox processors of an application waited on one IOutboxSignal, so a commit that wrote a message on one context woke the processor of every context. UseOutboxCore on the Entity Framework Core builder now registers a signal for its context, with the DbContext type as the service key, and the outbox and the processor of the context use it. MessagingDbContextServices is registered once per context type, so the commit interceptor signals the context that committed.
…ests

The tests replaced the outbox signal with ResilientOutboxSignal, because an interceptor could signal the disposed signal of another service provider. The interceptors now read the signal of the application that created the context, so the tests run with the signal that the outbox registers and the helper is removed.
The outbox middleware always stored a message in the IMessageOutbox registered in the container. An internal overload of DefaultMessageBus.PublishAsync and SendAsync now takes the outbox for one dispatch and sets it as a dispatch feature. The outbox middleware stores the message there, whatever its kind and SkipOutbox() flag, and the scheduling middleware stores a scheduled message there instead of in the scheduler store, after it has checked that the transport supports scheduling. IMessageOutbox moves from Mocha.Outbox to Mocha for this. Publish, send and request initialize their dispatch context in one method, and a scheduled publish or send passes its time in its options. The pipeline tests cover a dispatch that carries its outbox.
IMessageBus.PublishAsync writes to the outbox at once, through the connection of the first outbox context, and needs an open transaction to be atomic with business changes. dbContext.Outbox(bus) returns a DbContextOutbox whose PublishAsync and SendAsync run the dispatch pipeline and add the envelope to the context as an OutboxMessage entity, so the next SaveChanges writes entity changes and messages in one transaction, on any context that has an outbox. A message with a scheduled time is staged the same way, and the outbox processor hands it to the scheduling store of the transport after commit. A save that would write staged messages without a transaction is rejected, a publish or send that throws stages nothing, and the outbox only accepts the IMessageBus of the application that registered it. On .NET 8 the method throws NotSupportedException.
…d through the DbContext outbox

The tests save staged messages inside explicit, external, enlisted and ambient transactions and assert that the messages are delivered after commit and discarded after rollback, that a save without a transaction is rejected when automatic transactions are disabled, that a retried save or execution strategy delivers once, and that staged messages follow the change tracker when a context is cleared, pooled or saved again.
The tests assert the exceptions for a bus from another application or service provider, a bus that wraps the message bus, a context without an outbox or without the outbox entity in its model, and .NET 8, and that contexts created through a factory, from another scope or with options resolved from dependency injection are accepted.
The tests assert that a scheduled message is written with the business changes, handed to the native scheduler of the PostgreSQL transport or to the Postgres fallback store after commit, kept in the outbox when the hand-off fails, rejected before staging when the transport has no scheduler, and staged regardless of SkipOutbox(). The test project references the PostgreSQL transport for the native scheduler, and the CookieCrumble xunit and analyzer projects.
The tests assert that the outbox processor delivers a staged message with the body and headers it was prepared with, also on a retry, records a failed send on the outbox send span, delivers rows with malformed optional addresses and with a scheduled time that has already passed, routes by the RabbitMQ routing key of the stored envelope, and that the outbox queries still work against the existing table. Cases that use dbContext.Outbox(bus) are added to the tests for several contexts and for options resolved from a disposed scope.
…rator

The generator registered and validated message types only at IMessageBus call sites. A message type published or sent only through dbContext.Outbox(bus) was not registered by the generated module and not checked against the serializer context in AOT mode (MO0018). DbContextOutbox.PublishAsync and SendAsync are now handled like the IMessageBus methods.
The reliability page gets a section on dbContext.Outbox(bus) with the supported contexts and edge cases, and the scheduling page a section on scheduling through it. The pipeline, observability, handler registration and migration pages say where dbContext.Outbox(bus) behaves differently from IMessageBus, including SkipOutbox() having no effect, and the migration guide covers the new OutboxMessage constructor argument.
MessagingDbContextServices is registered once per context type, so the unkeyed lookup that DbContext.Outbox compared the services of the context with found nothing, and every bus was rejected as belonging to another application. The check now resolves the services of the context type from the service provider of the bus.
…essages

The commit interceptor signals only for a context that is marked as having written a message, and nothing marked a context for messages staged through DbContext.Outbox. A save without a database transaction did not signal at all, so staged messages waited for the next poll. Staging now marks the context, and OutboxSaveChangesInterceptor signals after a save that ran without a database transaction, or when the ambient transaction completes if there is one.
…x tests

The tests registered their outbox signal without a service key, which the outbox of a context no longer resolves, and four tests used the removed ResilientOutboxSignal. They now register the signal with the DbContext type as the service key, and the tests that need a working signal use the one the outbox registers.
@tobias-tengler
tobias-tengler force-pushed the tte/mocha-dbcontext-outbox branch from 0372218 to ebb9308 Compare November 23, 2026 13:31
@tobias-tengler
tobias-tengler force-pushed the tte/mocha-ef-outbox-contexts branch from c4b0ad1 to 020e827 Compare November 23, 2026 13:31
@PascalSenn
PascalSenn force-pushed the tte/mocha-ef-outbox-contexts branch from 020e827 to 57c54d3 Compare November 29, 2026 11:33
@PascalSenn
PascalSenn removed this pull request from stack #11019 November 29, 2026 11:33
@PascalSenn
PascalSenn added this pull request to stack #11103 November 29, 2026 11:33
@tobias-tengler
tobias-tengler removed this pull request from stack #11103 November 30, 2026 10:04
@tobias-tengler
tobias-tengler changed the base branch from tte/mocha-ef-outbox-contexts to main November 30, 2026 10:05

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

📚 documentation This issue is about working on our documentation. 🌶️ mocha

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant