wtorek, 24 lutego 2015

When to use dependency injection ?

Dependency injection is a great pattern that implements Inversion Of Control. I wrote about it in my first post.

Overusing a pattern is as bad as not using any architecture at all. It's called overengineering. As I mentioned before, it's hard to draw the line between no architecture and too much architecture.

How do we know when to use dependency injection and when don't ?

As mentioned here, this are great examples for when to use DI:

  • You need to inject configuration data into one or more components.
  • You need to inject the same dependency into multiple components.
  • You need to inject different implementations of the same dependency.
  • You need to inject the same implementation in different configurations.
  • You need some of the services provided by the container.

I also mentioned that creating an interface for every class just for the sake of it, might be a bad idea. It breaks RAP and YAGNI rules.

So what if we really want to use DI and play right by SOLID, but not overdo it ?

Breaking SOLID

If you stop using DI for some modules, doesn't that mean that you break the dependency inversion principle ?


"High-level modules should not depend on low-level modules. Both should depend on abstractions"


I was really confused so I sought help on StackOverflow asking:




I was lucky to get an answer from a StackOverflow veteran. You should read it carefully. It states that you should seek common behaviour from all the modules and try to extract one generic interface (an abstraction). I won't get into detail, because it's all described here in examples:

- Generic queries
Generic commands

Should I use IoC containers ?

The opinions are mixed. IoC are great in managing dependencies but involve a lot of complexity. There are books with hundreds of pages about IoC container frameworks.

In my opinion, you should consider IoC containers only if your project is really big, with a huge dependency tree.

One great thing about IoC is resolving dependency carrying. Dependency Carrying is when you create object A at the beginning and you carry it through all dependencies just because one class needs it.