将依赖项注入域模型的技术
我有一个域模型类型。它的众多属性之一需要 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不希望域对象进行翻译 - 相反,使用翻译服务并将域对象(或相关属性值)作为参数,并返回翻译后的值。例如,你可以简单地做
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
是的,这可能有意义,具体取决于您的情况。如果您总是避免将服务注入实体,那么这可能会导致贫乏的域模型 这是一种反模式。
需要实例化实体的代码可以通过使用工厂来屏蔽额外的构造函数参数,工厂负责依赖注入。
NHibernate 还可以通过构造函数将服务注入到实体中: http:// fabiomaulo.blogspot.com/2008/11/entities-behavior-injection.html
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