Dependency Injection using Unity Container in ASP.NET MVC

Dependency Injection using Unity Container in 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 it. 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 this article, I am going to discuss how to use the Microsoft Unity Container with an ASP.NET MVC5 application for dependency injection.

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

Create a New ASP.NET MVC 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 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 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 location where you need to create the project. Finally, click on the “OK” button as shown in the below image.

Dependency Injection using Unity Container in MVC 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. So, in order to do so, 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 below.

Unity Container - Select MVC Template

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.

Unity Container

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

Unity Container with Asp.Net MVC5 for dependency injection

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

Unity Container with Asp.Net MVC5 for dependency injection

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.

Unity Container with Asp.Net MVC5 for dependency injection

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.

Unity Container with Asp.Net MVC5 for dependency injection

Creating the Class Library Projects with the solution:

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.

So, right-click on the solution and click on Add => New Project as shown below

Unity Container with Asp.Net MVC5 for dependency injection

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 below.

Unity Container with Asp.Net MVC5 for dependency injection

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

Unity Container with Asp.Net MVC5 for dependency injection

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

Institution Class

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 Class

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; }
    }
}
Creating ServicesCL class Library Project:

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

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 below.

Once you click on the OK button, it will add the ServicesCL class library project into the solution as shown below.

Unity Container with Asp.Net MVC5 for dependency injection

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, select the reference folder and click on the add reference option, which will open the add reference window. From that window, select the solution option which is under the Projects section.  Next, Select the EntitiesCL checkbox and click on the Ok button as shown below.

Unity Container with Asp.Net MVC5 for dependency injection

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 then we need to implement the interfaces with concrete classes.

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

InstitutionService Class

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

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

CourseService Class

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"
            };
        }
    }
}

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.

Unity Container with Asp.Net MVC5 for dependency injection

Configuring the Components with the Unity Container:

Let’s first register all our components with the unity container. As we have two service classes, so we need to register those classes within the RegisterComponents method of the UnityConfig class 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 register this method within the Application_Start method of Global.asax file. So, modify the Global.asax file as shown below.

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 MVCUsingUnity web application.

Now we are going to display these institution and course information in our web application. I’ll add a new Empty Controller called Institution to our MVC application by right-clicking Controllers folder as shown below.

Unity Container with Asp.Net MVC5 for dependency injection

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

Unity Container with Asp.Net MVC5 for dependency injection

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.

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.

Unity Container with Asp.Net MVC5 for dependency injection

Next click on Add button which will create 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.

How to implement Dependency Injection using Unity Container in MVC Application

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 Microsoft Unity Container in 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 article.

3 thoughts on “Dependency Injection using Unity Container in ASP.NET MVC”

Leave a Reply

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