Overview
Domain events help implement:- Loose coupling between aggregates
- Side effects from domain operations
- Integration between bounded contexts
- Audit trails and notifications
- Eventual consistency patterns
Installation
Key Components
Domain Event Base
All domain events inherit from a base class:Domain Event
Has Domain Event Interface
Entities that raise events implementIHasDomainEvent:
IHasDomainEvent
Domain Event Service
Domain Event Service
Creating Domain Events
Define domain events in the domain designer:Custom Domain Event
Raising Domain Events
Raise events from entity methods:Raising Events
Event Handlers
When using with MediatR (Intent.MediatR.DomainEvents module):Event Handler
Multiple Handlers
Multiple handlers can respond to the same event:Multiple Handlers
Event Publishing
Automatic Publishing with EF Core
When using Intent.EntityFrameworkCore.Interop.DomainEvents, events are automatically published on SaveChanges:Automatic Publishing
Manual Publishing
Manual Publishing
Event Ordering
Control event handling order when needed:Event Ordering
Practical Examples
Order Processing Workflow
Order Workflow
Integration Events
Convert domain events to integration events:Integration Events
Error Handling
Error Handling
Testing
Testing
Best Practices
Immutable Events
Make domain events immutable with readonly properties to prevent tampering.
Clear Naming
Use past-tense names (CustomerRegistered, OrderPlaced) to indicate completed actions.
Event Data
Include sufficient data in events to avoid additional queries in handlers.
Idempotent Handlers
Design handlers to be idempotent in case events are processed multiple times.
Related Modules
- MediatR Domain Events - MediatR integration
- Entities - Domain entity generation
- Domain Services - Domain service generation
- EF Core Interop - Automatic event publishing
