域驱动设计模式 - 从域访问存储库 [英] Domain-driven design pattern - accessing repository from domain

查看:108
本文介绍了域驱动设计模式 - 从域访问存储库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在将域驱动的设计模式应用到我们的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?

推荐答案

是的,我建议创建一个服务来执行电子邮件。您可以在与域模型相同的项目中创建与服务交互的界面,但在单独的项目中提供服务的实现,以便从模型到服务没有硬依赖。依赖是相反的 - 从服务到模型。这也为实施单元测试创​​造了一个更好的设置,以确保您的服务是根据应用程序调用的,因为您现在可以在单元测试中模拟服务。

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.

这篇关于域驱动设计模式 - 从域访问存储库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆