Implementing the Inversion of Control Pattern in C#

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.

Fig 1.0
Fig 1.0

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.

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.

Fig 2.0
Fig 2.0

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 reading!



Related Articles

Comments

  • Dev

    Posted by Richard on 06/27/2013 12:03pm

    this is not IoC, this is simple ploymorphism, by the use of an Interface. Take a look at AutoFac, this is a good DI and is simple to implement. eg:: class HomeController { public ICustomer cust; } and then in the Application_Start, you simple wire up the .RegisterType() job done. no need to worry about creating a Customer object every time a HomeController is instantiated, AutoFac does it all for you.

    Reply
  • dev

    Posted by Richard on 06/27/2013 12:02pm

    this is not IoC, this is simple ploymorphism, by the use of an Interface. Take a look at AutoFac, this is a good DI and is simple to implement. eg:: class HomeController { public ICustomer cust; } and then in the Application_Start, you simple wire up the .RegisterType() job done. no need to worry about creating a Customer object every time a HomeController is instantiated, AutoFac does it all for you.

    Reply
  • Too many typos

    Posted by Mike on 06/21/2013 06:49am

    There are too many typos in your examples. Roughly 50% of them.

    Reply
  • Mr.

    Posted by Varun Gautam on 05/02/2013 05:13am

    This is really a very good article in simple language which is easy to understand.

    Reply
  • Did you mean...?

    Posted by András on 04/24/2013 04:50am

    VehicleController vehicleController = new VehicleController(vehicle); vehicleController.Accelerate(); vehicleController.Brake(); instead of VehicleController vehicleController = new VehicleController(vehicle); vehicle.Accelerate(); vehicle.Brake(); ?

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Hurricane Sandy was one of the most destructive natural disasters that the United States has ever experienced. Read this success story to learn how Datto protected its partners and their customers with proactive business continuity planning, heroic employee efforts, and the right mix of technology and support. With storm surges over 12 feet, winds that exceeded 90 mph, and a diameter spanning more than 900 miles, Sandy resulted in power outages to approximately 7.5 million people, and caused an estimated $50 …

  • With JRebel, developers get to see their code changes immediately, fine-tune their code with incremental changes, debug, explore and deploy their code with ease (both locally and remotely), and ultimately spend more time coding instead of waiting for the dreaded application redeploy to finish. Every time a developer tests a code change it takes minutes to build and deploy the application. JRebel keeps the app server running at all times, so testing is instantaneous and interactive.

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds