Click here to Skip to main content
15,741,692 members
Articles / Web Development / HTML
Posted 28 Dec 2016


10 bookmarked

Using Unity Framework in ASP.NET MVC 5

Rate me:
Please Sign up or sign in to vote.
5.00/5 (8 votes)
28 Dec 2016CPOL5 min read
In this article we will learn how to use Unity framework with ASP.NET MVC 5 application to register and resolve dependent objects.

[Note: Need to enable and restore NuGet Package to run the code.]


In this article we will learn how to use Unity framework with ASP.NET MVC 5 application to register and resolve dependent objects. First we will have a brief look at Unity Framework and then create a demo application in order to understand its usage with ASP.NET MVC 5.

Prerequisite: Good to have basic knowledge of MVC and Unity framework.

What is Unity Framework

Unity is a DI framework. Purpose of Unity framework is to inject the dependencies to the dependent object. Injecting the dependency to the dependent object is called Dependency Injection (DI). For more information, please have a look at Developer's Guide to Dependency Injection Using Unity

Overview of the Demo Application

We will create a demo application using ASP.NET MVC 5 and will see how to use unity to inject the dependencies. As we know each big application has multiple modules and may use services. Sometime a service uses another components to achieve the its objective. Services may be dependent on each other if required. Similar kind of scenario we will try replicate to understand the power of Unity. We will create a simple demo web application. Application will have two modules and will be consuming three kinds of services.

Let’s say we are going to develop an application for a Bank which will have two modules namely Account Info and Fund Transfer. Under Account Info module user can see their accounts detail. Under Fund Transfer module user can transfer the fund from one account to another.

To achieve the above mentioned functional requirement, let’s create an application using ASP.NET MVC 5 application called RichBankDemoApp. In the same solution we will add a class library project called RichBank.Services. RichBank.Services will be providing required service to RichBankDemoApp. RichBank.Services is not actual service but it is representation of the real service. RichBankDemoApp application will be using CustomerService, AccountService and FundTransferService. So let’s implement these three services in RichBank.Services projct. Here we are not targeting to any database. For demo purpose, three services will be giving hardcoded data. RichBank.Services project structure is shown below. Code is not described here since it’s very easy to understand.

RichBank Services project

As we discussed above RichBankDemoApp application will be having two modules called AccountInfo and FundTransfer. To separate these two modules, Areas is used. If you are new to Areas in ASP.NET MVC. Please have a look here.


Now using Manage NuGet Packages, Unity 4.0.1 version can be downloaded which is compatible with ASP.NET MVC 5. To download Unity 4.0.1, In solution explorer right click on References folder. Click on "Manage NuGet Packages" option. Manage NuGet Packages window will be opened. Go to online then search for Unity. Unity will be available, then click on Install button and click on Close button. Manage NuGet Packages automatically will download and add the references of two libraries which are Microsoft.Practices.Unity and Microsoft.Practices.Unity.Configuration.

Manage NuGet Packages

UnityConfig.cs file will be added to App_Start folder. UnityConfig is a static class which has a static method called RegisterComponents. Inside of this method we need to register all required dependencies.

Registering Dependencies: Open UnityConfig.cs file from App_Start, inside of RegisterComponents method all dependency need to be registered. Following code shows how to register the dependencies.

public static void RegisterComponents()
      var container = new UnityContainer();
      container.RegisterType<icustomerservice, customerservice="">();
      container.RegisterType<iaccountservice, accountservice="">();
      container.RegisterType<ifundtransferservice, fundtransferservice="">();
      DependencyResolver.SetResolver(new UnityDependencyResolver(container));

In above code, first UnityContainer is created to register dependencies. Then all dependencies are registered to the container. Here while registering, mapping is done between interface and class which implements that interface. Finally SetResolver method is used to set Unity Resolver for the application. Here we are creating a new UnityDependencyResolver using container and passes into SetResolver.
Note: There are various overloads available of RegisterType method to registers a type with the container. At the appropriate time, the container will build an instance of the registered type. For more information about RegisterType is available here.

Account Info Module: Account Info module will contain account related information. To get the account detail, AccountInformationController controller will need to interact AccountService. In AccountInformationController we will not create the instance of AccountService using new keyword instead of that we will pass IAccountService to the constructor of the AccountInformationController. Already we have registered this service to UnityContainer. So whenever AccountInformationController will be constructed instance of AccountService will be create by unity and it will be available in AccountInformationController. Following code shows the implementation of AccountInformationController.

public class AccountInformationController : Controller
    private IAccountService accountService;

    public AccountInformationController(IAccountService accountService)
       this.accountService = accountService;

    public ActionResult Index()
          //For demo purpose hardcoded CustomerId is passed
          List<account> allTrainings = accountService.GetAllAccountInfo(111);
          return View(allTrainings);

    public ActionResult GetAccountDetail(string accountNumber)
        Account accountdetail = accountService.GetAccountDetail(Convert.ToInt32(accountNumber));
        return Json(accountdetail);

AccountInformation view is created using HTML and jQuery code. Complete code is available with downloaded sample. Following image shows the layout of the view.

AccountInfo View

Fund Transfer Module: This module provides the options to do Fund transfer. User needs to select a particular type. Form will be available to perform Fund transfer. After clicking on “Transfer Amount” button. Filled amount will be transferred to selected account number. After completion of transfer process Current balance of From Account will be shown on the same form. To perform above task FundTransferController will be using FundTransferService and AccountService. Following code shows the implementation of FundTransferController.

public class FundTransferController : Controller
      private IFundTransferService fundTransferService;
      private IAccountService accountService;

      public FundTransferController(IFundTransferService fundTransferService, IAccountService accountService)
          this.fundTransferService = fundTransferService;
          this.accountService =  accountService;

      public ActionResult Index()
           var fundTransferTyoesList = fundTransferService.GetFundTransferTypes();
           return View(fundTransferTyoesList);
      public ActionResult PerformTransaction()
          return View();

Layout to do Fund transfer will look as shown below.

AccountInfo View


In this article, we had a walkthrough to use Unity with ASP.NET MVC 5. We saw how Unity is helpful for injecting dependencies in classes. Thanks for reading. Your comments and suggestions for improvement are most welcome.


  1. MSDN - Dependency Injection Using Unity
  2. Stackoverflow Discussion on Microsoft Unity


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Written By
Software Developer
India India
I am a Software Developer working on Microsoft technologies. My interest is exploring and sharing the awesomeness of emerging technologies.

Comments and Discussions

QuestionManaging both MVC and Web API Controllers in same project Pin
Arjun Menon U.K8-Nov-20 9:49
Arjun Menon U.K8-Nov-20 9:49 
GeneralMy vote of 5 Pin
Shamim Uddin24-Oct-18 23:37
professionalShamim Uddin24-Oct-18 23:37 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.