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

可紊 提交于 2019-12-20 10:43:55

问题


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?


回答1:


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.

e.g. 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.

e.g. 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?




回答2:


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.




回答3:


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:



来源:https://stackoverflow.com/questions/18086266/in-ddd-who-should-be-resposible-for-handling-domain-events

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!