Search code examples
dependency-injectiondomain-model

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?


Solution

  • 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