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

  • I still do not get it

    Posted by Gilda on 01/21/2015 01:22pm

    If it was as you say in the comments... vehicleController had to implement the IVehicle interface, too.

    Reply
  • DEV

    Posted by Faisal on 10/15/2014 09:43pm

    Really good article. very simple to understand!

    Reply
  • Mr.

    Posted by Supratheesh on 06/25/2014 06:39am

    You wrote eg as: VehicleController vehicleController = new VehicleController(vehicle); vehicle.Accelerate(); vehicle.Brake(); But I strongly believe.. it should be as given below: VehicleController vehicleController = new VehicleController(vehicle); vehicleController.Accelerate(); vehicleController.Brake(); in

    Reply
  • 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

  • Complex hybrid environments can make it difficult to track interdependencies, increasing the risk of disrupting critical business services. In this white paper by EMA, you'll learn how application discovery and dependency mapping can help you: Meet granular targets for availability, cost, and time-to-revenue for cloud services. Accelerate mean time to repair (MTTR) while communicating better with stakeholders. Manage even the most complex hybrid environments more efficiently and effectively Understand the …

  • When individual departments procure cloud service for their own use, they usually don't consider the hazardous organization-wide implications. Read this paper to learn best practices for setting up an internal, IT-based cloud brokerage function that service the entire organization. Find out how this approach enables you to retain top-down visibility and control of network security and manage the impact of cloud traffic on your WAN.

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date