233
CHAPTER 6 | Tackle Business Complexity in a Microservice with DDD and CQRS Patterns
However, when the domain events class is static, it also dispatches to handlers immediately. This
makes testing and debugging more difficult, because the event handlers with side-effects logic are
executed immediately after the event is raised. When you’re testing and debugging, you just want to
focus on what is happening in the curr
ent aggregate classes; you don’t want to suddenly be
redirected to other event handlers for side effects related to other aggregates or application logic.
This is why other approaches have evolved, as explained in the next section.
The deferred approach to raise and dispatch events
Instead of dispatching to a domain event handler immediately, a better approach is to add the
domain events to a collection and then to dispatch those domain events
right before
or
right
after
committing the transaction (as with SaveChanges in EF). (This approach was described by Jimmy
Bogard in this post
A better domain events pattern
.)
Deciding if you send the domain events right before or right after committing the transaction is
important, since it determines whether you will include the side effects as part of the same transaction
or in different transactions. In the latter case, you need to deal with eventual consistency across
multiple aggregates. This topic is discussed in the next section.
The deferred approach is what eShopOnContainers uses. First, you add the events happening in your
entities into a collection or list of events per entity. That list should be part of the entity object, or
even better, part of your base entity class, as shown in the following example of the Entity base class:
Dostları ilə paylaş: