views:

34

answers:

2

I'm not sure for which use cases one should to use DI in the application. I know that injecting services like PlaceService or CalculationService etc fits very well but should I also create my domain objects with DI like a User? What is if the User has only one constructor which requires a first and lastname. Is this solveable with DI?

Should I use DI to create the instances for Set/List interfaces or is this pure overkill?

I use guice primarily.

+1  A: 

The rule I use is, in general, to favor dependency injection, except where the object can be constructed with purely primitive values and there is no / a minimal chance that the object might be replaced by another implementation.

However, for domain objects, particularly if your objects do not constitute an anemic domain model, i.e., where objects are just bags of getters and setters, it can be useful to have objects that, for example, can persist themselves to a datastore, etc. For those sort of objects, dependency injection and Salve can be a powerful combination.

Guice has a specific solution to the type of problem posed by objects like your User object called AssistedInject, though similar things are also possible with other lightweight containers or using something the builder or adapter patterns.

ig0774
+1 See my answer for additional guidance.
Mark Seemann
+1  A: 

The answer by ig0774 is a good starting point. In addition, I would like to offer this rule of thumb:

In the terminology of Domain-Driven Design, you should DI for services, but not for entities or value objects.

In other words, DI fits well with conceptually long-lived, stateless objects of which there are usually one or a known number in use.

Mark Seemann