Introduction
Inversion of control (IoC) is a simple principle that dictates that an external entity should send messages to programmer's objects in order to perform some specialized action or to allow the programmer to override some logic. It can be used in order to reduce the level of coupling in an application and thus allowing reuse of objects. Coupling is reduced in IoC by inverting how your class obtains external object references or configuration, so that your class only has references to Interfaces and the concreted object references are provided externally. In his famous article Martin Fowler calls this Dependency Injection, because an external module(container) injects the dependency into your classes.
There are three types of Dependency Injection.
- Constructor Injection
- Setter Injection
- Interface Injection
Constructor Injection is where the container injects the implementations of the class dependencies through the constructor. For this to work your class must declare a constructor with everything it needs injected. Setter Injection uses a setter instead of a constructor.
IoC Implementations
An IoC implementation fulfills the following three criteria;
- There's a container, which manages objects for you.
- The container generally controls creation of objects.
- The container resolves dependencies between objects it manages.
Some popular implementations of IoC in Java are Hivemind, PicoContainer, and Spring (This is not just a IoC container)
Recently, we find implementations of IoC in C# also. Two most notable such implementations are Spring.NET and Castle.