Inversion Dependency vs Dependency Injection vs IOC Container

A lot of developers make the mistake of claiming when it comes to Inversion Dependency, Dependency Injection and IOC Containers they are very similar. In actual fact they are complete different concepts. This blog attempts to distinguish the difference in theory.

 

Inversion Dependency

Inversion dependency is a pattern that focus’ on the higher level layer defining the interface for classes in the lower level layers.

Layer One

As you can see above, the lower level classes implement Ifruit, which means as the lower level creates more fruits such as apple and tomato, the higher level will not change because its only dependency is the interface Ifruit. This results in the higher level not needing to know about the concrete classes in the lower layer.

Now how does banana get instantiated for a higher level service to use if you do not want the higher level service to know banana exists?

 

Dependency Injection

Dependency injection is required to inject concrete classes to services (including the service itself) that need to use them but don’t know the class exists (only knows about the interface). Some of the popular methods to inject these dependencies to services are:

  • Via the constructor – everything the class/service needs to do its job is passed into the constructor.
  • Using property setters – everything the class/service needs to do its job passed through the property setter (hopefully before its needed)

 

IOC Container- Inversion of control

Basically speaking the IOC container host the business logic of mapping concrete classes with interfaces. The resolver actually uses the IOC’s business logic to inject the correct concrete class for each interface that the service needs to use.

Layer Two

The ins and outs of when classes are injected and instantiated depends on which dependency injection tool being used. Some third party dependency injection tools available are Microsoft’s Unity, Ninject and Autofac.