rss search

Inversion of Control in a Nutshell

line

Inversion of Control is a software design in which objects are bound together at run time. They are not known during compile time. There are several type of inversion of control:

  1. Factory Pattern. A class method accepts a parameters in order to return requested object after initializing it.
  2. Service Locator Pattern.
  3. Dependency Injection.
    • Constructor Injection like in Asp.NET MVC
    • Setter injection like (Properties in C# and setter method in Java)
    • An interface injection.

In dependency injection, a class requests all the dependent objects via constructor parameters and assign them to a private field.

public class Samurai {
    public IWeapon Weapon { get; private set; }
    public Samurai(IWeapon weapon) 
    {
        this.Weapon = weapon;
    }
}

and Binder/Assembler instantiates the class Samurai, passes in Weapon concrete object (instantiated). As you see you don’t have any control over when the object will be created so this means you gave the control to the IoC Framework instead of instantiated it in your class at your will.

But there must be a place where you need to tell which types should be bound to which type. That’s why modules are here. Each DI Frameworks might have their own way doing this but as we are using NInject here  the following code shows the class where we tell the Framework binding instructions:

public class WarriorModule : NinjectModule
{
    public override void Load() 
    {
        this.Bind<IWeapon>().To<Sword>();
    }
}

As you can see we’re telling the framework to bind Sword class to IWeapon so when we need an weapon, FW will inject Weapon object.

So as you can see there are several benefits of doing Inversion of Control using Dependency Injection:

  1. When you need to change the implementation details by changing the concrete class, all you need to do is to change the binding in the module instead of changing it everywhere in the project.
  2. It gives you more centralized location where you can manage your bindings.
  3. Whenever you need a new object, all you have to do is to request from within method parameter and you will have it.

Sample codes are taken from NInject.org, an open source library.



Leave a Reply