Could you tell me your opinion that which layer is the right one to place domain event handlers in DDD? For example, I have application service to add a new contract and I’d like to send an email notification to the contact person, when the contract has added, so is that email sender (which handle ContractAdded event) application service or domain service or something else?
0
I place domain event handlers in application layer.
Domain event is a way to tell the outside layers (or outside world) that something happened in the domain layer. What to do with the event depends on the application. Application may notify user about changes or may call another domain to do something. Application is responsible for orchestrating domain operations in reaction on user actions, web requests or domain events.
1
I place Domain Event Handlers in Domain layer as a domain interface IDomainEventHandler
.
An example of a Domain Event Handler is a policy that subscribes to certain domain event in order to initialize a new transaction (e.g: in order to trigger a new domain command), therefore it makes sense to have it in Domain layer since it’s related to business logic.
We could think of an example where an order is confirmed and therefore an invoice request should be created.
We have an event OrderConfirmedEvent
that has happened. A policy in our domain would be in charge of subscribing to this event and creating a domain command RequestInvoice
that will be handled by the command handler and dealt by it accordingly.
If we had this event handler in application layer it would mean that the application layer, in addition to orchestrating user’s actions, would execute some business logic, which seems incorrect.
However we have
3
The original DDD book (Evans 2004) explains the application layer as a thin layer which exercises domain objects in response to the user’s action. Typical event handlers for domain events therefore don’t belong in the application layer.
It may make sense to place some of them in the domain layer, as long as you don’t break the layering by creating an upwards dependency.
If you have a infrastructure layer that is below the domain layer, the event handler can’t be there since it would break the layering.
If you have an adapters layer that is above the domain layer, you can create an event handler there. Check out Hexagonal architecture.