Ben Aston
Ben Aston

Reputation: 55729

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 there another functional pattern I can use?

Does anyone have any relevant experience they can share?

Upvotes: 5

Views: 1925

Answers (2)

Wim Coenen
Wim Coenen

Reputation: 66723

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

Upvotes: 0

Tomas Aschan
Tomas Aschan

Reputation: 60574

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

Upvotes: 4

Related Questions