[Note: Need to enable and restore NuGet Package to run the code.]
Introduction
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.
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.
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));
}
</ifundtransferservice,>
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()
{
List<account> allTrainings = accountService.GetAllAccountInfo(111);
return View(allTrainings);
}
public ActionResult GetAccountDetail(string accountNumber)
{
Account accountdetail = accountService.GetAccountDetail(Convert.ToInt32(accountNumber));
return Json(accountdetail);
}
}
</account>
AccountInformation view is created using HTML and jQuery code. Complete code is available with downloaded sample. Following image shows the layout of the 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.
Conclusion
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.
References
- MSDN - Dependency Injection Using Unity
- Stackoverflow Discussion on Microsoft Unity