Command handlers and domain events
To keep aggregates separated, usually, interactions with other aggregates and other Bounded Contexts are done through events. It is good practice to store all the events when they are created during the processing of each aggregate, instead of executing them immediately, in order to prevent event execution from interfering with the ongoing aggregate processing. This is easily achieved by adding the following code to the abstract Entity
class defined in the Entities and value objects subsection of this chapter, as follows:
public List<IEventNotification> DomainEvents { get; private set; }
public void AddDomainEvent(IEventNotification evt)
{
DomainEvents ??= new List<IEventNotification>();
DomainEvents.Add(evt);
}
public void RemoveDomainEvent(IEventNotification evt)
{
DomainEvents?.Remove(evt);
}
Here, IEventNotification
is an empty interface that’s used to mark classes as events.
Event processing is usually...