Saturday, December 6, 2008

Inversion of Control (Dependency Injection)

There are three types of Inversion of Control. They are as follows:

1. IoC Type I (Interface Injection)
2. IoC Type II (Setter Injection)
3. IoC Type III (Constructor Injection)

Though it is difficult to remember these types but I recommend you to remember these as these are commonly used during conversation between software architecture designers. This is part of architect’s language.

In Inversion of control the library only does part job by specifying an abstract solution. For the rest of the solution, they have to rely on the code using that library. i.e. generic code has to call to application specific code. It is explained as Hollywood principle: “Don’t call us, we will call you”. So, in Inversion of control based frameworks, it is the reusable code which calls application specific client code.

Inversion of control is about calling user code from library code. Earlier we used to do this in the form of function pointers. In this case, library defines only the abstract implementation of task and more concrete implementation is provided by the user code. Other option to provide decoupling is the Service Locator option. The difference is the way they provide the implementation class to the user of the library. Service locator hides the implementation classes but at least you need to be able to see the locator. So instead of many couplings, you have this additional coupling with the locator.

Inversion of control is not a new concept but it has already been there. Event driven programming is one application of Inversion of Control. You can see that you define event handlers which are then called by the framework following the Hollywood principle. In Microsoft world, this concept is presented as dependency injection. In functional programming, monad is an example of IoC.

No comments: