Dependency Injection using Unity Container in MVC

Dependency Injection using Unity Container in ASP.NET MVC Application

In this article, I am going to discuss how to implement Dependency Injection using Unity Container in ASP.NET MVC Application. Please read our previous article before proceeding to this article, where we discussed how to implement the Dependency Injection Design Pattern in C# by taking the different types of scenarios. As part of this article, we are going to discuss the following pointers in detail.

  1. What is the Unity Container?
  2. How to implement Dependency Injection Design Pattern in MVC Application using Unity Container?
What is the Unity Container?

The Dependency Injection Design Pattern allows us to inject the dependency objects into a class that depends on them. Unity is a Dependency Injection Container that can be used for creating and injecting the dependency object using either constructor, method, or property injections. So here in this article, I am going to discuss how to use the Microsoft Unity Container with an ASP.NET MVC 5 application for dependency injection.

Here we are going to create an ASP.NET MVC web application for the course listing website. In this application Institutions and Courses are our main entities. So let’s start the implementation step by step.

Create a New ASP.NET MVC 5 Application

Open Visual Studio and create a new project. To do so, select “File => New => Project” as shown in the below image.

Dependency Injection using Unity Container in ASP.NET MVC Application

Once you clicked on the “Project” link a new dialog will pop up. From that window, we are going to select web templates from the left pane which is under the “Installed => Templates => Visual C#” section. Then from the middle pane select “ASP.NET Web Application”. Provide a meaningful name for the project such as “MVCUsingUnity” and select the location where you need to create the project. Finally, click on the “OK” button as shown in the below image.

Create a New ASP.NET MVC 5 Application

Once you click on the OK button, then a new dialog will pop up for selecting Project Templates. From this template, we are going to choose “MVC” as the project template. Here we are not going to use any authentication i.e. going to use No Authentication. So, in order to choose No Authentication, just click on the “Change Authentication” button, a new dialog will pop up with the name Change Authentication and from there we need to select the “No Authentication” option. Finally, click on the “OK” button as shown in the below image.

Dependency Injection using Unity Container

Once you click on the OK button, It will take some time to create the project for us. Now we need to install the Unity Container for MVC 5 application.

Installing Unity.Mvc5 Library from NuGet:

In order to install Unity.Mvc5 Library using the NuGet, we need to go to the Package Manager Console and execute the Install-Package Unity.Mvc5 Command. To do so, go to the Tools menu and select NuGet Package Manager => Package Manager Console as shown in the below image.

Installing Unity.Mvc5 Library from NuGet

Once you select the Package Manager Console, then the Package Manager Console tab will open. Type Install-Package Unity.Mvc5 command and press the enter button as shown in the below image.

Install-Package Unity.Mvc5

It will take some time to install the necessary packages. Once the installation completes you will get the following messages.

Dependency Injection using Unity Container in MVC

UnityConfig.cs

Once the installation is completed, then it will create a class file with the name UnityConfig.cs inside the App_Start folder as shown below. This is the class file where we need to register all our components.

UnityConfig.cs class file

If you open the UnityConfig.cs class file, then you will find the following UnityConfig class with the RegisterComponents() method. Within this RegisterComponents() method we need to register all our components. How to register the components that we will discuss later part of this article.

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

namespace MVCUsingUnity
{
    public static class UnityConfig
    {
        public static void RegisterComponents()
        {
     var container = new UnityContainer();
            
            // register all your components with the container here
            // it is NOT necessary to register your controllers
            // e.g. container.RegisterType<ITestService, TestService>(); 
            DependencyResolver.SetResolver(new UnityDependencyResolver(container));
        }
    }
}
Creating the Class Library Projects:

Let’s add two Class Library projects with the name EntitiesCL and ServicesCL into the solution. Within the EntitiesCL project, we are going to create all our entities or model classes. Similarly, within the ServicesCL project, we are going to implement the business logic that is required for our application.

Adding EntitiesCL Class Library Project to our Solution:

To add the EntitiesCL class Library Project to our solution, right-click on the solution and then select Add => New Project option from the context menu as shown in the below image.

Adding EntitiesCL Class Library Project to our Solution

From the Add New Project window, select Visual C# from the left pane, and from the right pane select Class Library template. Provide the name for the class library as EntitiesCL. Finally, click on the OK button as shown in the below image.

EntitiesCL Class Library Project

Once you click on the OK button, it will add the EntitiesCL class library project to the solution as shown in the below image.

Unity Container in ASP.NET MVC

Once the EntitiesCL class library project is created, then we need to add the following entities within the EntitiesCL class library project.

Institution Entity

Right-click on the EntitiesCL class library project, then add a class file with the name Institution.cs, and then copy and paste the following code into it. This is a very simple entity with 4 properties.

namespace EntitiesCL
{
    public class Institution
    {
        public long InstitutionID { get; set; }
        public string Name { get; set; }
        public string Telephone { get; set; }
        public string Address { get; set; }
    }
}
Course Entity

Right-click on the EntitiesCL class library project, then add a class file with the name Course.cs, and then copy and paste the following code into it. This is a very simple entity with 4 properties.

namespace EntitiesCL
{
    public class Course
    {
        public long CourseID { get; set; }
        public long InstitutionID { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
    }
}
Adding ServicesCL Class Library Project to our Solution:

Next, we need to create the ServicesCL Class Library project. To do so, right-click on the solution and then select Add => New Project option from the context menu as shown in the below image.

Adding EntitiesCL Class Library Project to our Solution

From the Add New Project window, select Visual C# from the left pane, and from the right pane select Class Library template. Provide the name for the class library as ServicesCL. Finally, click on the OK button as shown in the below image.

Adding ServicesCL Class Library Project to our Solution

Once you click on the OK button, it will add the ServicesCL class library project to the solution, and currently, you can see three projects in the solution as shown in the below image.

ServicesCL Class Library Project

Now we need to add a reference to the EntitiesCL project from the ServicesCL project. as we are going to use the entities which we created in the EntitiesCL project. To do so, from the ServicesCL project, select the reference folder and then click on the add reference option, which will open the add reference window. From the add reference window, select the solution option which is under the Projects section. Next, Select the EntitiesCL checkbox and click on the Ok button as shown in the below image.

Unity Container in ASP.NET MVC Application

Now we need to create two service classes to implement the business logic. One for institutions and another one for courses. As we are going to implement dependency injection, so this should be interface-based. That means we need to create interfaces with declarations and then we need to implement the interfaces with concrete classes.

IInstitutionService Interface

Right-click on the ServicesCL class library project, then add a class file with the name IInstitutionService.cs, and then copy and paste the following code into it. The following interface defines one abstract method.

using EntitiesCL;
namespace ServicesCL
{
    public interface IInstitutionService
    {
        Institution GetInstitutionByID(long institutionID);
    }
}
InstitutionService Class

Right-click on the ServicesCL class library project, then add a class file with the name InstitutionService.cs, and then copy and paste the following code into it. The following class is inherited from the IInstitutionService interface and implements the GetInstitutionByID abstract method.

using EntitiesCL;
namespace ServicesCL
{
    public class InstitutionService : IInstitutionService
    {
        public Institution GetInstitutionByID(long institutionID)
        {
            return new Institution
            {
                InstitutionID = institutionID,
                Name = "Demo Institution",
                Address = "Demo Address",
                Telephone = "0123456789"
            };
        }
    }
}
ICourseService Interface

Right-click on the ServicesCL class library project, then add a class file with the name ICourseService.cs, and then copy and paste the following code into it. The following interface defines one abstract method.

using EntitiesCL;
namespace ServicesCL
{
    public interface ICourseService
    {
        Course GetCourseByID(long courseID);
    }
}
CourseService Class

Right-click on the ServicesCL class library project, then add a class file with the name CourseService.cs, and then copy and paste the following code into it. The following class is inherited from the ICourseService interface and implements the GetCourseByID abstract method.

using EntitiesCL;
namespace ServicesCL
{
    public class CourseService : ICourseService
    {
        public Course GetCourseByID(long courseID)
        {
            return new Course
            {
                CourseID = courseID,
                Description = "Demo course description",
                InstitutionID = 1,
                Title = "Demo Course Title"
            };
        }
    }
}
Adding EntitiesCL and ServicesCL Reference in MVCUsingUnity MVC Web Application:

We need to add references to EntitiesCL and ServicesCL class library projects within the MVCUsingUnity MVC Web Application project as shown in the below image. This is because, within our MVC web application, we are going to use both the model classes as well as service classes.

Adding EntitiesCL and ServicesCL Reference in MVCUsingUnity MVC Web Application

Configuring the Components with the Unity Container in ASP.NET MVC Application:

Let’s first register all our components with the Unity Container in the ASP.NET MVC application. The components here are nothing but the service classes. As we have two service classes, so we need to register these two classes within the RegisterComponents method of the UnityConfig class. Unity container provides the RegisterType() and Resolver() methods for registering and resolving the dependency objects.

Registering the Components:

Before Unity Container resolves the dependencies, we need to register the type-mapping with the container, so that it can create the correct object for the given type. To do so, Unity Container provides one method called RegisterType() to register a type mapping.  Basically, RegisterType() configures which class to instantiate for which interface or base class. For example, if you want the Unity container to create and supply an object of the InstitutionService class whenever it needs to supply a dependency of the IInstitutionService interface, then we first need to register it as follows.

container.RegisterType<IInstitutionService, InstitutionService>();

Here, container.RegisterType<IInstitutionService, InstitutionService>() requests Unity Container to create an object of the InstitutionService class and inject it through a constructor whenever you need to inject an object of IInstitutionService. Similarly, if you want the Unity container to create and supply an object of the CourseService class whenever it needs to supply a dependency of the ICourseService interface, then you need to register it as follows.

container.RegisterType<ICourseService, CourseService>();

Here, container.RegisterType<ICourseService, CourseService>() requests Unity Container to create an object of the CourseService class and inject it through a constructor whenever you need to inject an object of ICourseService.

SetResolver:

So, after we register the component with the unity container, then we need to use the static SetResolver() method of the DependencyResolver class. The SetResolver method Provides a registration point for dependency resolvers, using the specified dependency resolver interface. With the above changes in place, your UnityConfig class file should look as shown below.

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

namespace MVCUsingUnity
{
    public static class UnityConfig
    {
        public static void RegisterComponents()
        {
            var container = new UnityContainer();

            // register all your components with the container here
            // it is NOT necessary to register your controllers
            
            container.RegisterType<IInstitutionService, InstitutionService>();
            container.RegisterType<ICourseService, CourseService>();
            
            DependencyResolver.SetResolver(new UnityDependencyResolver(container));
        }
    }
}

We need to run this RegisterComponets method as soon as our application start. So we need to call this method from the Application_Start method of the Global.asax file. The Application_Start method going to be run as soon as your application starts. So, modify the Global.asax file as shown below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace MVCUsingUnity
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            UnityConfig.RegisterComponents();
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }
}
Adding Controller to the MVCUsingUnity Web Application.

Now we are going to display these institutions and course information in our web application. Let us add a new Empty MVC 5 Controller called Institution to our ASP.NET MVC application. To do so, right-click on the Controllers folder and then select Add => Controller from the context menu which will open the below Add Scaffold window. From this window, select MVC 5 Controller – Empty option and then click on the Add button as shown in the below image.

Adding MVC 5 Controller

Once we click on the Add button it will open a popup for providing the controller name. Provide the controller name as Institution and click on the Add button as shown in the below image.

Dependency Injection using Unity Container in MVC

Generally, if we want to invoke the method of InstitutionService class within the InstitutionController, then we create an object of the InstitutionService class within the InstitutionController. As we are going to use the Dependency Injection Design Pattern using Unity Container, so it is the responsibility of the Unity Container to create the object of the InstitutionService class and then inject that object within the InstitutionController. Here we are going to use Constructor Dependency Injection. So we need to create a constructor with one parameter as shown below.

using ServicesCL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVCUsingUnity.Controllers
{
    public class InstitutionController : Controller
    {
        private IInstitutionService institutionService;
        public InstitutionController(IInstitutionService institutionService)
        {
            this.institutionService = institutionService;
        }
        public ActionResult Index()
        {
            return View(this.institutionService.GetInstitutionByID(1));
        }
    }
}
Adding View:

Let’s add a view to display the information. To do so, right-click on the Index action method and click on Add View which will open the below popup, simply click on the Add button.

Adding Index View

Once you click on the Add button it will create the Index.cshtml view. Copy and paste the following code within the Index.cshtml file.

@using EntitiesCL;
@model Institution

@{
    ViewBag.Title = "Institution";
}

<hr />
Institution ID : @(Model.InstitutionID)

<hr />
Institution Name : @(Model.Name)

<hr />
Institution Address : @(Model.Address)

<hr />
Institution Telephone : @(Model.Telephone)

That’s it. we are done, now run your application and try /Institution/Index. You should get the following output.

Dependency Injection using Unity Container in ASP.NET MVC Application

Lifetime Managers in Unity Container:

The Unity Container manages the lifetime of dependency objects that it resolves using the lifetime managers. The Unity container includes different lifetime managers for different scenarios. You can specify the lifetime manager in the RegisterType() method while registering the type mapping. Following are the lists of all lifetime managers.

Lifetime Managers in Unity Container

For example, the following code shows how to register a type-mapping with ContainerControlledLifetimeManager.
container.RegisterType<IInstitutionService, InstitutionService>(new ContainerControlledLifetimeManager());
The following code shows how to register a type-mapping with ContainerControlledLifetimeManager.
container.RegisterType<ICourseService, CourseService>(new TransientLifetimeManager());
The Unity Container Lifetime Manager classes belong to Unity.Lifetime namespace. The following is the complete code example.

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

namespace MVCUsingUnity
{
    public static class UnityConfig
    {
        public static void RegisterComponents()
        {
            var container = new UnityContainer();
            // register all your components with the container here
            // it is NOT necessary to register your controllers

            // e.g. container.RegisterType<ITestService, TestService>();

            container.RegisterType<IInstitutionService, InstitutionService>(new ContainerControlledLifetimeManager());
            container.RegisterType<ICourseService, CourseService>(new TransientLifetimeManager());

            DependencyResolver.SetResolver(new UnityDependencyResolver(container));
        }
    }
}

In the next article, I am going to discuss the Repository Design Pattern in C# with examples. In this article, I try to explain how to implement Dependency Injection using Unity Container in ASP.NET MVC Application step by step with an example. I hope this article will help you with your needs. I would like to have your feedback. Please post your feedback, question, or comments about this Dependency Injection using Unity Container in the ASP.NET MVC Application article.

12 thoughts on “Dependency Injection using Unity Container in MVC”

  1. Thanks, I was struggling with how set the IoC container on a MVC project. This was simple and quick. Thanks

  2. Hi,

    Nice article but I have a doubt. Upto creating, registering and resolving container is fine but what/where is it’s use here? In controller I can’t see that the container has been used anywhere. You’re passing the interface as constructor injection. That is fine but where is the use of container that you created using unity that is my doubt.

    public class InstitutionController : Controller
    {
    private IInstitutionService institutionService;
    public InstitutionController(IInstitutionService institutionService)
    {
    this.institutionService = institutionService;
    }
    public ActionResult Index()
    {
    return View(this.institutionService.GetInstitutionByID(1));
    }
    }

    1. @Diya, the Unity Container took care of object creation of InstitutionService upon adding the RegisterComponents in global.asax file. Try comparing this with previous constructor injection where we explicitly had create object and in parameter to constructor, in this Unity took care object creation.

Leave a Reply

Your email address will not be published. Required fields are marked *