将依赖项注入域模型的技术

发布于 2024-09-11 23:08:06 字数 228 浏览 2 评论 0原文

我有一个域模型类型。它的众多属性之一需要 ITranslationService 提供将其返回值翻译成适当语言的能力。

我是否应该将 ITranslationService 注入到域模型类型的构造函数中(从而必须在实例化类型的所有地方进行更改,并且在通过 NhIbernate 检索时必须关注初始化),即使它被类型的一小部分使用(一个许多属性);或者我可以使用其他功能模式吗?

有没有人有相关经验可以分享一下?

I have a domain model type. One of its numerous properties requires an ITranslationService to provide the ability to translate its return value into the appropriate language.

Should I inject the ITranslationService into the constructor of the domain model type (thereby having to alter everywhere the type is instantiated and having to be concerned about initialisation when retrieved via NhIbernate), even though it is used by a tiny part of the type (one of many properties); or is there another functional pattern I can use?

Does anyone have any relevant experience they can share?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

我不希望域对象进行翻译 - 相反,使用翻译服务并将域对象(或相关属性值)作为参数,并返回翻译后的值。例如,你可以简单地做

var translatedString = yourServiceInstance.Translate(theDomainObject.Property);

I would not expect the domain object to do the translation - instead, use the translation service with the domain object (or the relevant property value) as a parameter, and return the translated value. For example, you could simply do

var translatedString = yourServiceInstance.Translate(theDomainObject.Property);
扶醉桌前 2024-09-18 23:08:06

我应该注射吗
ITranslationService 进入
领域模型类型的构造函数

是的,这可能有意义,具体取决于您的情况。如果您总是避免将服务注入实体,那么这可能会导致贫乏的域模型 这是一种反模式。

需要实例化实体的代码可以通过使用工厂来屏蔽额外的构造函数参数,工厂负责依赖注入。

NHibernate 还可以通过构造函数将服务注入到实体中: http:// fabiomaulo.blogspot.com/2008/11/entities-behavior-injection.html

Should I inject the
ITranslationService into the
constructor of the domain model type

Yes, that may make sense, depending on your situation. If you would always avoid the injection of services into entities, then that might lead to an anemic domain model which is an anti-pattern.

Code which needs to instantiate entities can be shielded from the extra constructor argument by using a factory, which takes care of the dependency injection.

NHibernate can also inject services into an entity via the constructor: http://fabiomaulo.blogspot.com/2008/11/entities-behavior-injection.html

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文