DDD Step By Step
A Practical Guide to Domain Driven Design

Browse by Tags

  • How *not* to inject services in entities by Jérémie Chassaing

    I’ve seen lot of people asking where and how to inject services in entities. The services in question are often repositories by the way… The response is simple : - DO NOT inject services in entities ! - Ok I see, you’re against dependency injection - NO, I'm not against dependency injection, I use it a lot. - You can still use a static service locator… - I avoid service locator when I can, especially when the service locator must be static… – So you’ll get an anemic object model ! - I don’t think so. Injecting services in entities is wrong You’ll find me a bit presumptuous, but I say it again : Injecting services in entities is wrong . Nesting objects is not a problem from an OO point of view, but we’re talking about a special kind of objects, entities. Entities are all about their state management, and this state management can require several objects. Code infrastructure objects like lists or dictionary to handle collection of data, Object oriented constructs to leverage code maintenance techniques like strategies. Entities don’t have to be classes with public setters and getters… you should even avoid this to keep you entities in a consistent state. But there is no reason for an entity to keep a reference on a service, since...