What is a domain event? An event is something that has happened in the past. A domain event is, something that happened in
the domain that you want other parts of the same domain (in-process) to be aware of. The notified
parts usually react somehow to the events.
An important benefit of domain events is that side effects can be expressed explicitly.
For example, if you’re just using Entity Framework and there has to be a reaction to some event, you
would probably code whatever you need close to what triggers the event. So the rule gets coupled,
implicitly, to the code, and you have to look into the code to, hopefully, realize the rule is
implemented there.
On the other hand, using domain events makes the concept explicit, because there’s a
DomainEvent
and at least one
DomainEventHandler
involved.
For example, in the eShopOnContainers application, when an order is created, the user becomes a
buyer, so an
OrderStartedDomainEvent
is raised and handled in the
ValidateOrAddBuyerAggregateWhenOrderStartedDomainEventHandler
, so the underlying concept is
evident.
In short, domain events help you to express, explicitly, the domain rules, based in the ubiquitous
language provided by the domain experts. Domain events also enable a better separation of concerns
among classes within the same domain.
It’s important to ensure that, just like a database transaction, either all the operations related to a
domain event finish successfully or none of them do.
Domain events are similar to messaging-style events, with one important difference. With real
messaging, message queuing, message brokers, or a service bus using AMQP, a message is always
sent asynchronously and communicated across processes and machines. This is useful for integrating
multiple Bounded Contexts, microservices, or even different applications. However, with domain
events, you want to raise an event from the domain operation you’re currently running, but you want
any side effects to occur within the same domain.
The domain events and their side effects (the actions triggered afterwards that are managed by event
handlers) should occur almost immediately, usually in-process, and within the same domain. Thus,
domain events could be synchronous or asynchronous. Integration events, however, should always be
asynchronous.
229
CHAPTER 6 | Tackle Business Complexity in a Microservice with DDD and CQRS Patterns