领域驱动设计模式 - 从领域访问存储库
我一直致力于将领域驱动设计模式应用到我们的 Web 应用程序中。我们遇到的问题之一是避免使用实体内的存储库。
例如,我们有一些实体,其方法将触发电子邮件。因此,我们必须有权访问电子邮件模板(存储在数据库中),并在数据库队列表中创建新的电子邮件记录。我们目前通过访问这些实例中的存储库违反了该模式。
在这些情况下我们应该使用“服务”层还是“应用程序”层(我们有很多)?有没有更好的方法来解决这个问题?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,我建议创建一项服务来执行电子邮件的发送。您可以在与域模型相同的项目中创建与服务交互的接口,但在单独的项目中提供服务的实现,以便模型与服务之间不存在硬依赖关系。依赖关系是相反的——从服务到模型。这还为实现单元测试创建了更好的设置,以确保您的服务在应该的情况下被调用,因为您现在可以在单元测试中模拟服务。
剩下要做的一件事是确保在创建这些对象类型之一时注入您的服务。因此,您将把对象创建推迟到存储库。或者更好的是,使用依赖项注入框架来为您解决依赖项。
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.
领域应该是持久无知的。您不应该从内部“与存储库交谈”。
在您的场景中 - 我会引发域事件(例如“客户是购买东西”)并处理从外部发送的电子邮件。
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.