In an ASP.NET Core modular monolith, how would Admissions publish an ApplicantAdmitted event that Fees handles in-process, and what can go wrong?
answer
- event record in the publisher's Contracts
- handlers resolved from the request scope
- a handler exception reaches the caller
- two DbContexts, two commits
- in-process now, broker when extracted
basics
~20 sAdmissions defines ApplicantAdmitted in its Contracts project and publishes it through a dispatcher that resolves registered handlers from DI; Fees registers one. Dispatch runs inside the request, so a failing handler hits the caller and the modules commit separately.
solid answer
~50 sThe event is a record in `University.Admissions.Contracts`, so Fees depends on the contract, not on Admissions' internals. Admissions publishes it through an `IModuleEventBus` whose in-process implementation resolves `IEnumerable<IModuleEventHandler<ApplicantAdmitted>>` from the current scope and awaits each one; Fees registers `CreateTuitionInvoice` as a handler inside `AddFeesModule`. MediatR's `IPublisher.Publish` with `INotification` does the same job, now under Lucky Penny's licence. The pitfalls come from it being **in-process and synchronous**: the Fees handler runs inside the admission request, adding latency; its exception propagates to the Admissions endpoint; and because each module has its own `DbContext`, the admission and the invoice are two `SaveChangesAsync` calls, so publishing after the first commit can leave an admitted student with no invoice. Publishing before the commit is worse: Fees acts on an admission that may roll back. Durable delivery needs an outbox, and a broker once modules run in separate processes.
code
csharp · 16 linesinternal sealed class InProcessEventBus(IServiceProvider services) : IModuleEventBus
{
public async Task Publish<TEvent>(TEvent @event, CancellationToken ct)
{
foreach (var handler in services.GetServices<IModuleEventHandler<TEvent>>())
await handler.Handle(@event, ct);
}
}
// inside AdmitApplicantHandler, Admissions module
applicant.Admit(); // tracked entity, loaded earlier
await db.SaveChangesAsync(ct); // commit first
await bus.Publish(new ApplicantAdmitted(applicant.StudentId, applicant.Programme, year), ct);
// inside AddFeesModule
services.AddScoped<IModuleEventHandler<ApplicantAdmitted>, CreateTuitionInvoice>();go deeper
Know that a module can announce something happened with an event record and that other modules register handlers for it.
Explain where the event contract lives, how a simple bus resolves handlers from DI, and why publishing happens after SaveChangesAsync.
Walk through the failure modes: separate commits, propagating exceptions, latency, scopes in background dispatch, and when an outbox becomes necessary.
Decide when in-process dispatch stops being enough and a broker earns its operational cost, and keep the contract stable across that change.
## Why events between modules In the university monolith, admitting an applicant should create a tuition invoice. If Admissions called Fees directly, Admissions would depend on Fees and grow a reference for every module that cares about admissions. An **event** reverses that: Admissions announces a fact, `ApplicantAdmitted`, and any module that cares subscribes. Admissions does not know who listens. ## The contract The event belongs to the **publisher**, in its public Contracts project: - `University.Admissions.Contracts` holds `public sealed record ApplicantAdmitted(Guid StudentId, string Programme, int Year)`. - Fees references `University.Admissions.Contracts`, never `University.Admissions`. - The record carries what subscribers need, so Fees does not have to call back to Admissions to look up the student. ## In-process dispatch A minimal in-process event bus is a few lines on top of Microsoft.Extensions.DependencyInjection: 1. A shared abstractions project defines `IModuleEventHandler<TEvent>` and `IModuleEventBus`. 2. Fees registers `services.AddScoped<IModuleEventHandler<ApplicantAdmitted>, CreateTuitionInvoice>()` inside `AddFeesModule`. 3. The bus resolves `GetServices<IModuleEventHandler<TEvent>>()` from the current scope and awaits each handler in turn. 4. Admissions' handler calls `await bus.Publish(new ApplicantAdmitted(...), ct)`. MediatR offers the same shape: the event implements `INotification`, handlers implement `INotificationHandler<T>`, and `IPublisher.Publish` calls them, by default one after another with `ForeachAwaitPublisher`. MediatR 14 is a Lucky Penny product under the RPL-1.5 or a paid licence, which is one reason teams write the few lines themselves. ## What goes wrong | Problem | Cause | Mitigation | |---|---|---| | Admission saved, invoice missing | `AdmissionsDbContext` committed, then the Fees handler threw | outbox with retries, or a shared cross-context transaction | | Invoice for an admission that rolled back | event published before `SaveChangesAsync` | publish only after the commit | | Admissions endpoint returns 500 for a Fees bug | handler exception propagates through `Publish` | catch and log per handler, or dispatch asynchronously | | Slow admission requests | every handler runs inside the request | move slow work to a background queue | | Hidden coupling to handler order | handlers awaited in registration order | make handlers independent of each other | The first row is the important one. Each module has its own `DbContext`, so the admission and the invoice are two separate commits. In-process dispatch gives no delivery guarantee: if the process dies between them, the event is lost. Teams that need the invoice to exist reliably store the event in an **outbox** table in the same transaction as the admission and deliver it afterwards. Scopes matter too. Handlers resolved from the request scope receive the request's scoped services, including Fees' own scoped `FeesDbContext`. If dispatch is moved to a background queue, the handler must create its own scope, because the request scope is disposed when the response completes. ## Making handlers safe to run twice Once events are retried, whether by an outbox, a broker or a person re-running a failed job, a handler can see the same event more than once. `CreateTuitionInvoice` must therefore be **idempotent**: - Give the invoice a natural key from the event, such as `StudentId` plus academic `Year`, and put a unique index on it in `FeesDbContext`'s configuration. - Before creating an invoice, check whether one with that key already exists, and return quietly if it does. - If two deliveries race, the unique index turns the second insert into a `DbUpdateException` the handler can treat as "already done". Idempotent handlers make the in-process version more forgiving too: a failed admission request can be retried without double-billing the student. ## In-process versus a broker In-process events are the right start in a monolith: no infrastructure, easy debugging, one deployment. A message broker becomes worth its cost when modules run in separate processes, when delivery must survive restarts without an outbox of your own, or when other systems subscribe too. Keeping the event as a contract record and the bus as an interface means that switch replaces one registration, not every publisher and handler.
- Why must the IModuleEventBus be registered as scoped rather than singleton in this design?The bus takes `IServiceProvider` and resolves handlers from it. Registered as scoped, it receives the request's scoped provider, so handlers get the request's `FeesDbContext`. As a singleton it would capture the root provider, and resolving scoped handlers from the root either fails under scope validation in Development or creates services that live for the whole process.
- If Fees' handler fails, should Admissions roll back the admission?Usually not: the admission is a fact in Admissions' own data, and Fees' failure is Fees' problem to retry. That is why the reliable version records the event in an outbox inside Admissions' transaction and delivers it with retries, rather than coupling the two modules' commits together.
In-process publishing is the admissions officer walking the signed letter to the fees office and waiting at the counter while it is filed: quick and simple, but if the fees clerk drops it, the student is admitted with no invoice and nobody comes back for it.
- In-process events are guaranteed to be delivered once the publisher returns.
- Publishing before SaveChangesAsync is safer because Fees sees the change sooner.
- Event records belong in the subscriber's project so it controls the shape.
- Fees' handler joins the publisher's transaction automatically because both run in one request.
- A handler exception is swallowed so the publisher never sees it.