Dependency Injection in Asp.Net MVC 4.6 Framework

Asp.net MVC Dependency Injection implementation example using C#.

What is Dependency Injection in Asp.Net MVC?
Dependency injection is a design pattern, a technique that helps to inject dependent object of a class without changing the concrete implementation.

Before we learn DI with example let’s understand, Some Terminology we often hear while talking about dependency injection implementation.

IoC Inversion of Control

IoC (Inversion of Control) is a principal like "Don't Call Us, We'll Call You", IoC is the ability to differ the implementation of a contract.

Dependency Injection (DI)

DI is a implementation technique as per IoC (Inversion of Control) principal.

How to implement Dependency injection

Let's think of our regular office as example, in our office many events happen though out the year, like birthdays every month, CSR Event, Annual function event, Diwali, Success celebration etc.

dependency injection IoC in asp.net mvc

As you can see in above example both classes Office and BirthDayEvent are tightly coupled with each other.

Now suppose we want to create new event called CRSEvent, then again we need to create a new instance of CRSEvent class in my office class, similarly whenever we want to create a new type of event every time we have to create a new instance in Office class. - That's the problem

Now the solution is we need to move the control of events to some different place, not in Office class, that means, inside Office class we are not going to create any instance of any type of Event. This is called Inversion of Control (IOC).


Now let's see how we can create a solution using dependency injection design pattern.

dependency injection IoC in asp.net mvc

This is how Dependency Injection (DI) implemented as per IOC principal

namespace WTRConsoleApplication
{
    public interface IOfficeEvent
    {
         void Execute();
    }
    public class BirthDayEvent : IOfficeEvent
    {
        public void Execute()
        {
            //celebrating all employees birthday for current month
        }
    }
    public class CRSEvent : IOfficeEvent
    {
        public void Execute()
        {
            //organising CRS
        }
    }
    public class AnnualFunctionEvent : IOfficeEvent
    {
        public void Execute()
        {
            //celebrating Annual Function
        }
    }
        
    public class Office
    {
        IOfficeEvent _event = null;
        public Office(IOfficeEvent ioe)
        {
            _event = ioe;
        }
        public void Celebrate()
        {
            _event.Execute();
        }
    }
}
Dependency Injection via Constructor

In above example DI has been implmented via Constructor, Let's look at the code again.

public class Office
    {
        IOfficeEvent _event = null;
        public Office(IOfficeEvent ioe)
        {
            _event = ioe;
        }
        public void Celebrate()
        {
            _event.Execute();
        }
    }
Dependency Injection via Method

Injection can be implemented via method also.

public class Office
    {
        IOfficeEvent _event = null;
      
        public void Celebrate(IOfficeEvent ioe)
        {
             _event = ioe;
            _event.Execute();
        }
    }

Advantage of Implementing Dependency Injection (DI)
Classes are loosely coupled, Due to decoupling, code become more reusable, thus improved code maintainability and testing and cleanliness.

Register UnityContainer- Dependency Injection

Now, if you run the project you will see the error message "No parameterless constructor defined for this object".

So, Just open your NugetPackage Manager, then install Unity and Unity.Mvc5 package.

Create a new file called UnityConfig.cs at App_Start folder, and add the following code.

using System.Web.Mvc;
using Unity;
using Unity.Mvc5;

namespace WTRConsoleApplication
{
public static class UnityConfig
{
    public static void RegisterComponents()
    {
		var container = new UnityContainer();
            
        container.RegisterType<IOfficeEvent, OfficeEvent>();
            
        DependencyResolver.SetResolver(new UnityDependencyResolver(container));
    }
}
}

Now register the UnityContainer service at Application_Start of Global.asax.cs like below.

public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
     
        UnityConfig.RegisterComponents();
    }
}
Dependency Injection through MVC Controller

Finally, call the office service method from your MVC controller

Look how service instance getting created through constructor, and accessing service method

using System.Web.Mvc;
namespace WebTrainingRoom.Controllers
{
public class UserController : Controller
{
IOfficeEvent _officeSerice;
public UserController(IOfficeEvent officeSercice)
{
_officeSerice = officeSercice;
}
public ActionResult Index()
{
_officeSerice.Execute();
return View();
        }
    }
}

Hope, now you understand how to implement dependency injection in asp.net mvc application!

You may be interested in following tutorials:

 
Dependency Injection IOC
Aspnet MVC Training
Asp.net MVC tutorials, learn model view controllers with c#, develop database driven web application using Asp.net MVC framework.
Hire .Net Developer
Free Tutorials
ASP.NET MVC Interview Questions Answers
Dependency injection in C#
Asp.Net MVC C# Examples | Join Asp.Net MVC Course | Asp.net Core Tutorial