Domain-driven design pattern - accessing repositor

2019-04-27 13:47发布

问题:

I've been working on applying the domain-driven design pattern to our web application. One of the issues we've ran into is avoiding having to use a repository from within an entity.

For example, we have some entities whose methods will trigger an email. So we have to have access to the email template (stored in the database), as well as create a new email record in the database queue table. We are currently violating the pattern by accessing the repositories in these instances.

Should we be utilizing a "service" or "application" layer in these instances (we have lots of them)? Is there a better way to get around this issue?

回答1:

Yes, I would recommend creating a service to perform the sending of the email. You can create an interface for interacting with the service in the same project as the domain model, but provide the implementation of the service in a separate project so that there is no hard dependency from the model to the service. The dependency is reversed - from service to model. This also creates a better setup for implementing unit tests to ensure that your service is called under the cirucmstances that it should be since you'll now be able to mock the service in your unit tests.

The one thing that is left to do is make sure that your service is injected any time one of these object types is created. So, you'll defer object creation either to the repository. Or even better, use a dependency injection framework to resolve the dependency for you.



回答2:

Domain should be persistence ignorant. You shouldn't "talk with repository" from within.

In Your scenario - I would raise domain event (e.g. "Customer is purchasing something") and handle e-mail sending from outside.