Inversion of Control ( IoC )

IoC or Inversion of Control is a technique in which components within application receive objects from the framework instead of instantiating the classes themselves.

In early days, if we need an object of Manager class, we used to write:

Manager manager = new Manager();

In IoC technique, first we create an interface named IEmployee and the Manager class implements it. Now, when we write:

IEmployee employee;

the framework will automatically find the class that implements this interface, which is Manager in our case. Hence in the background this line becomes:

IEmployee employee = new Manager();

The advantage is that our code is not dependent on Manager class. This allows us to easily replace Manager class with some other class without touching the code that uses it.

Autofac

Autofac is an IoC container for Microsoft .NET. It manages the dependencies between classes so that components within application are not dependent on each other. This way, application is easy to scale and manage.

IoC Example
  1. Create a new MVC project. Next, we need to add the Autofac and Autofac.Mvc dependency in our project.
  2. Go to Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution..
  3. In the Search box, enter Autofac and after it finds, click the Install button.
  4. Again, search for Autofac.Mvc and install.
  5. Now we will create an interface and a class in a new Services folder. The class will contain a single method to add two numbers. Right click on the project and create a new folder named Services.
  6. Next create two classes named IDataService.cs and DataService.cs in the Service folder. Here is the code for both of them:
    IDataService.cs

    using System;
    namespace DependencyDemo.Services
    {
       public interface IDataService
       {
           int Add(int a, int b);
       }
    }

    DataService.cs

    using System;
    namespace DependencyDemo.Services
    {
       public class DataService : IDataService
       {
           public int Add(int a, int b)
           {
                return a+b;
           }
       }
    }
  7. Now, we will add configuration for Autofac. Create the file AutofacConfig.cs in App_Start folder and add following code in it:
    using System.Web.Mvc;
    using Autofac;
    using DependencyDemo.Services;
    using Autofac.Integration.Mvc;
    
    namespace DependencyDemo
    {
       internal class AutofacConfig
       {
          public static void ConfigureContainer()
          {
            var builder = new ContainerBuilder();
    
            // Register dependencies in controllers
            builder.RegisterControllers(typeof(MvcApplication).Assembly);
    
            // Register dependencies in filter attributes
            builder.RegisterFilterProvider();
    
            // Register dependencies in custom views
            builder.RegisterSource(new ViewRegistrationSource());
    
            builder.RegisterType<DataService>().As<IDataService>().InstancePerRequest();
    
            var container = builder.Build();
    
            // Set MVC DI resolver to use our Autofac container
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
          }
       }
    }

    I know the above code is a bit complex but we need to worry only about the bolded line.

  8. To initiate the above configuration, add following line to the Application_Start() method of Global.asax file:
    AutofacConfig.ConfigureContainer();
  9. There will be an existing controller named HomeController in the Controllers folder. Add following code to this controller:
    private IDataService dataService;
    
    public HomeController(IDataService dataService)
    {
       this.dataService = dataService;
    }
  10. Now, add following two actions that will help us in adding two numbers:
    public ActionResult Add()
    {
       return View();
    }
    
    [HttpPost]
    public ActionResult Add(int a,int b)
    {
       return Content((a+b).ToString());
    }

    Now, we will add a view for the first Add action. Put this HTML in the view file:

    @{
     Layout = null;
    }
    <!DOCTYPE html>
    <html>
        <head>
           <title>Add two numbers</title>
        </head>
    <body>
        <div> 
            <form method="post" action="add">
                <input type="text" name="a"/> 
                <input type="text" name="b" /> 
                <input type="submit" value="Add" />
            </form>
        </div>
    </body>
    </html>

Run the application and visit the URL:

http://localhost:port/project_name/home/add