简体   繁体   中英

In DDD, who should be resposible for handling domain events?

Who should be responsible for handling domain events? Application services, domain services or entities itself?

Let's use simple example for this question.

Let's say we work on shop application, and we have an application service dedicated to order operations. In this application Order is an aggregate root and following rules, we can work only with one aggregate within single transaction. After Order is placed, it is persisted in a database. But there is more to be done. First of all, we need to change number of items available in the inventory and secondly notify some other part of a system (probably another bounded context) that shipping procedure for that particular order should be started. Because, as already stated, we can modify only one aggregate within transaction, I think about publishing OrderPlacedEvent that will be handled by some components in the separate transactions.

Question arise: which components should handle this type of event?

I'd like to:

1) Application layer if the event triggers modification of another Aggregate in the same bounded context.

2) Application layer if the event trigger some infrastructure service.

eg An email is sent to the customer. So an application service is needed to load order for mail content and mail to and then invoke infrastructure service to send the mail.

3) I prefer a Domain Service personally if the event triggers some operations in another bounded context.

eg Shipping or Billing, an infrastructure implementation of the Domain Service is responsible to integrate other bounded context.

4) Infrastructure layer if the event need to be split to multiple consumers. The consumer goes to 1),2) or 3).

For me, the conclusion is Application layer if the event leads to an seperate acceptance test for your bounded context.

By the way, what's your infrastructure to ensure durability of your event? Do you include the event publishing in the transaction?

These kind of handlers belong to application layer. You should probably create a supporting application service's method too. This way you can start separate transaction.

I think the most common and usual place to put the EventHandlers is in the application layer . Doing the analogy with CQRS, EventHandlers are very similar to CommandHandlers and I usually put them both close to each other (in the application layer).

This article from Microsoft also gives some examples putting handlers there. Look a the image bellow, taken from the related article:

积极和处理程序

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM