Implementing the Inversion of Control Pattern in C#

csharp wallpaper

In my previous post I spoke about the first principle of SOLID. In this post I explain last two principle. I hope it will be clear enough.

Dependency Inversion Principle (DIP)

Dependency Injection Principle states that there should be more abstraction between the higher level module and the lower level module. It is required to have loose coupling so that any change in the low level modules will not affect or there will be minimal impact at the higher level module. The ideal scenario would be when you write components for other applications to consume.

Inversion-of-Control-Pattern-1

In the example provided in Fig 1.0 VehicleController is the higher level module, which consumes and uses the lower level module Car. If you want to change the vehicle to Truck instead of Car then VehicleController does not require any change if there is higher level of abstraction.

Inversion of Control (IoC)

Inversion of Control is a technique to implement the Dependency Inversion Principle in C#. Inversion of control can be achieved by using interfaces or abstract class. The rule is that the lower level modules should sign up the contract to a single interface and the higher level module will consume only modules that are implementing the interface. This technique removes the dependency between the modules.

Inversion-of-Control-Pattern

As shown in Fig 2.0 Car and Truck will implement the interface IVehicle and VehicleController will couple with the vehicles through the IVehicle interface thus increasing the level of abstraction between the layers.

Sample IoC implementation in C#

In this section we will see the implementation of the IoC technique in the C# language. In Visual Studio create a Console application project and name it IoCDemo. Now add classes named VehicleController, Car, Truck and an interface IVehicle. In a real work scenario these items will be in separate layers like Car and Truck in one layer, IVehicle interface in abstraction layer and VehicleController as the higher level module. I have clubbed everything into a single project as it is a sample code. Following is the sample C# code implementing IoC.

public class Car : IVehicle
{

    #region IVehicle Members

    public void Accelerate()
    {
        Console.WriteLine("Car accelerates...");
    }

    public void Brake()
    {
        Console.WriteLine("Car stopped.");
    }

    #endregion
}

public class Truck : IVehicle
{
    #region IVehicle Members

    public void Accelerate()
    {
        Console.WriteLine("Truck accelerates...");
    }

    public void Brake()
    {
        Console.WriteLine("Truck stopped.");
    }

    #endregion
}

public interface IVehicle
{
    void Accelerate();
    void Brake();
}

public class VehicleController
{
    IVehicle m_Vehicle;

    public VehicleController(IVehicle vehicle)
    {
        this.m_Vehicle = vehicle;
    }

    public void Accelerate()
    {
        m_Vehicle.Accelerate();
    }

    public void Brake()
    {
        m_Vehicle.Brake();
    }
}

class Program
{
    static void Main(string[] args)
    {
        IVehicle vehicle = new Car();
        //IVehicle vehicle = new Truck();

        VehicleController vehicleController = new VehicleController(vehicle);
        vehicle.Accelerate();
        vehicle.Brake();

        Console.Read();
    }
}

In the above code the products are completely decoupled from the consumer using the IVehicle interface. The object is injected into the constructor of the VehicleController class in reference with the interface IVehicle. The constructor where the object gets injected is called as Injection Constructor.

Inversion of Control Container

If you look at the code sample provided in the above section, the Car or Truck object creation is still present in the Main method, which is again a dependency. In IoC technique the creation of the object will also be delegated to a separate component or framework, which will take care of creating and injecting the dependency object. This is called dependency injection and the component accomplishing the task is called the IoC container.

There are many IoC containers readily available in the market; some of the popular ones are the following.

  1. Microsoft Unity framework
  2. Castle Windsor
  3. NInject

You can also create your own custom IoC container using reflection and generics in C#. I hope this article has provided enough information about the Inversion of Control pattern.

Happy coding!

One thought on “Implementing the Inversion of Control Pattern in C#

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.