الانتقال إلى المحتوى
.NETClean Architecture· 8 دقائق للقراءة

Domain Events Are Not Integration Events: Two Kinds of Events in a .NET App

A domain event is handled in-process, often before the commit. An integration event is a public contract that must leave only after the commit, and an outbox is how you get it there.

ReadIn

مقال كل يوم يفرق معاك

22 نوفمبر 2026
  • كاتب موثّق
  • .NET 10
محتويات المقال

The Ordering service raises OrderPlaced when an order is placed, and a handler already reserves stock for it. Shipping needs to know too, so someone adds a second handler that publishes the same event to the message broker. It works in every demo, until a customer double-clicks "Place order", the second save fails on a unique order number, and Shipping receives a message for an order that doesn't exist. A week later, a restart between a commit and a publish loses a message, and an order that does exist never ships.

The common misconception

The belief: domain events and integration events are the same thing, so a domain event can go straight to the message broker. An event is an event; why model it twice?

It's a reasonable reading of the sources. Microsoft's architecture guide says outright that, semantically, domain and integration events are the same thing: notifications about something that just happened. Both describe something that already happened and are named in the past tense, which matches Martin Fowler's description of a domain event as a record of something that happened. Vaughn Vernon, quoted in the same guide, suggests delivering domain events to asynchronous subscribers. But the guide follows that line with the one that matters: their implementation must be different.

What actually happens

Same fact, two audiences

A domain event is for the rest of your own domain. Microsoft's guide describes it as something you want other parts of the same domain, in-process, to be aware of, with handlers in the application layer that update other aggregates or start application actions. An integration event exists to propagate committed changes to other microservices, bounded contexts or external applications, and it always travels asynchronously, across processes, through an event bus. One is an internal call with a nicer shape. The other is a published API.

Domain events run before the commit; integration events must wait for it

The guide's reference app dispatches domain events right before SaveChanges, on purpose: handlers that use the same scoped DbContext add their changes to the same transaction, so the order and its side effects succeed or fail together. Integration events have the opposite rule. They should go out only if the entity was saved, otherwise it's as if the whole operation never happened.

A broker publish inside a domain event handler breaks that rule. In a test with EF Core 10 on SQLite, a handler published OrderPlaced to a fake broker, then SaveChangesAsync failed with UNIQUE constraint failed: Orders.Number. The broker held one message, and the order wasn't in the database.

After the commit isn't enough on its own

Moving the publish after SaveChangesAsync fixes that and opens the reverse gap: two writes, to the database and to the broker, with no transaction spanning both. The guide spells out the failure: if the service crashes after the database is updated but before the event is published, the system can become inconsistent. It advises against distributed transactions between the two and lists three ways out: full event sourcing, transaction log mining, or a table. In the test, a simulated crash between the commit and the publish left the order saved and the broker empty.

A domain event isn't a contract

Domain events may carry domain objects. The guide's own OrderStartedDomainEvent holds the Order entity, which is fine in-process. Put it on the wire and the entity's shape becomes your public API. In the test, serializing an event that carried an order with a back-reference from its lines threw JsonException: A possible object cycle was detected. Even without a cycle, renaming a domain property would break every consumer. Integration events are plain data-holding classes, and the guide recommends defining them per service rather than in a library shared across services.

The fix: translate at the boundary, stage in an outbox

C# OrderPlacedHandlers.cs
using Mediator;// Runs right before SaveChangesAsync, like every domain event handlerpublic sealed class PublishOrderPlaced(IMessageBus bus)    : INotificationHandler<OrderPlaced>{    public async ValueTask Handle(OrderPlaced e, CancellationToken ct)    {        // The domain event itself becomes the public message,        // and it leaves before the order is committed        await bus.PublishAsync(e, ct);    }}

The staged row is just the contract's type name and JSON payload, saved by the same SaveChangesAsync as the order. In the test, a failing save left no outbox row behind, and a successful one stored the order and its message together. A background service then publishes what's pending:

C# OutboxRelay.cs
using Microsoft.EntityFrameworkCore;public sealed class OutboxRelay(IServiceScopeFactory scopes, IMessageBus bus)    : BackgroundService{    protected override async Task ExecuteAsync(CancellationToken stop)    {        while (!stop.IsCancellationRequested)        {            using var scope = scopes.CreateScope();            var db = scope.ServiceProvider.GetRequiredService<ShopDb>();            var pending = await db.Outbox.Where(x => x.PublishedAt == null)                .OrderBy(x => x.Id).Take(50).ToListAsync(stop);            foreach (var m in pending)            {                // A crash between these lines sends it again next time                await bus.PublishAsync(m.Type, m.Payload, stop);                m.PublishedAt = DateTime.UtcNow;                await db.SaveChangesAsync(stop);            }            await Task.Delay(TimeSpan.FromSeconds(1), stop);        }    }}

That comment is the deal you accept. In the test, a relay that crashed after publishing and before marking the row sent the same message twice. An outbox gives you at-least-once delivery, so consumers must be idempotent: processing a message twice has to leave the same result as processing it once.

Domain eventIntegration event
AudienceYour own domain, in the same processOther services and applications
When it's handledUsually right before the commit, in the same transactionOnly after the commit, asynchronously
PayloadMay carry domain objectsPlain, versioned data that consumers depend on
DeliveryA method call; fails with the requestThrough a broker, at least once
Who owns the shapeThe domain model, free to changeA public contract, changed with care

How to apply it in your project

  1. Find publishes in domain event handlersSearch for broker, email and HTTP calls in code that runs before SaveChangesAsync, including SaveChanges overrides and interceptors.
  2. Define integration events as contractsCreate separate records with primitive fields and a version in the name, owned by the publishing service, and map domain events to them in explicit code.
  3. Stage them in an outboxAdd an outbox table and insert integration events in the same SaveChangesAsync as the business change.
  4. Relay, then make consumers idempotentPublish pending rows from a background service, and have every consumer detect duplicates or apply changes that are safe to repeat.

Key takeaways

  • Domain and integration events describe the same kind of fact for different audiences, so they're implemented differently.
  • Domain events usually run before the commit, in the same transaction; integration events must leave only after it.
  • Publishing from a domain event handler can announce data that was rolled back, and publishing after the commit can lose the message.
  • An outbox row saved with the business change closes that gap, at the price of at-least-once delivery.
  • Treat integration events as versioned public contracts and make every consumer idempotent.

📚 المصادر

  1. Domain events: design and implementation — .NET Architecture Guides, Microsoft Learn
  2. Implementing event-based communication between microservices (integration events) — .NET Architecture Guides, Microsoft Learn
  3. Subscribing to events: atomicity, outbox and idempotency — .NET Architecture Guides, Microsoft Learn
  4. Domain Event — Martin Fowler

التعليقات (0)