开发者

Techniques for dependency injection into a domain model

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 开发者_如何学Pythonthere another functional pattern I can use?

Does anyone have any relevant experience they can share?


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);


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜