Dependency injection is a very simple concept: if you have an object that interacts with other objects the responsibility of finding a reference to those objects at run time is moved outside of the object itself.
What does it mean for an object to "interact" with other objects? Generally it means
invoking methods or reading properties from those objects. So if we have a class
A that invokes method
Calculate on class
B, we can say that
A interacts with
In the following example we show class
A interacting with class
We can equally say that
B to fulfill a responsibility.
In this case, it not only invokes its method
Calculate but it also creates a new instance of that class.
In the following example, on the other side, the responsibility of getting a reference to an implementation of
a class of type
B is moved outside of
In this case we say that a dependency (
B) has been injected into
A, via the constructor.
Of course, you can also inject dependencies via a property (or even a regular method), like in the following example:
So this is all there is about dependency injection. Everything else just builds on this core concept.
Like for example Inversion Of Control (IoC) tools which helps you wiring together your objects at run time, injecting all dependencies as needed. So what exactly is Inversion of Control and how does it relate to Dependency Injection (DI)?
I like to associate IoC to the Hollywood Principle: "Don't call us, we'll call you". IoC is a design principle where
reusable generic code controls the execution of problem-specific code: it is a characteristic of many frameworks, where the application is built extending or customizing a common skeleton; you put your own classes at specific points and the framework will call you when needed.
You can use an IoC container as a framework to perform Dependency Injection on your behalf: you tell the container which are the concrete implementation classes for your dependencies and the container will make sure that your constructors or setters will be called with the right objects.
Therefore, IoC containers are just a convenience to simplify how dependency injection is handled. But even if you don't use one you could still manually perform dependency injection.
(If you want to have a look at how an IoC container works you can jump to my mini tutorial on Ninject).
Why is the concept of dependency injection important? Because by applying it, you simplify your design (separating the responsibility of using an object from the responsibility of retrieving that object) and your code becomes much easier to test, since you can mock out the dependencies substituting them with fake (stub) objects. But that is the subject for another post.