After successfully completion of nuget packages,check the solution explorer and you can see newly added UnityConfig class inside App_Start folder. That’s where we register all our components with the container.


3. Update Sample Application
first I’ll add two another Class Library projects called Entities and Services. There Entities project holds all the entity (model) classes we are going to use and Services project will be used to put our service classes.After adding two new projects your solution will look like this.

Now i added all required model classes(entities) in entities project.
Employee Class (Employee.cs)
namespace Entities
{
public class Employee
{
public int EmployeeId { get; set; }
public string EmployeeName { get; set; }
public string HomeTown {get;set;}
public int DepartmentId { get; set; }
}
}
Next I will add reference to Entities project from Services project and create service classes for Employee . And also I will add relevant interfaces for those classes.

IEmployeeService Interface:
using Entities;
namespace Services
{
public interface IEmployeeService
{
IList GetEmployeeBy();
}
EmployeeService Class (EmployeeService.cs):
using Entities;
namespace Services
{
public class EmployeeService:IEmployeeService
{
public IList GetEmployeeBy()
{
IList empList = new List();
empList.Add(new Employee() {EmployeeId=1001,EmployeeName="Rakesh Mahur",DepartmentId=111,HomeTown="Meerut" });
empList.Add(new Employee() { EmployeeId = 1001, EmployeeName = "Siddhart Tandon", DepartmentId = 111, HomeTown = "Lucknow" });
empList.Add(new Employee() { EmployeeId = 1002, EmployeeName = "Sumit Gupta", DepartmentId = 112, HomeTown = "Haldwani" });
empList.Add(new Employee() { EmployeeId = 1003, EmployeeName = "Avay Azad", DepartmentId = 113, HomeTown = "Patna" });
empList.Add(new Employee() { EmployeeId = 1004, EmployeeName = "Sachin Mittal", DepartmentId = 114, HomeTown = "Delhi" });
return empList;
}
}
}
4. Configure Unity:
Let’s register our components with the unity container. There first we have to update our UnityConfig class as below.
using Unity.Mvc5;
using Services;
namespace DIWithUnityMVC
{
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<IEmployeeService, EmployeeService>();
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
}
}
}
This RegisterComponents method can be called within the Application_Start method in Global.asax. We can update our Global.asax as below.
namespace DIWithUnityMVC
{
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);
}
}
}
5. Continue with Sample Application:
Now i am going to display these employee information in our web application. I’ll add new Empty Controller called Employee to our MVC application by right clicking Controllers folder.

Normally if we want to use our EmployeeService within the EmployeeController, we need to create instance of EmployeeService inside EmployeeController.
Dependency injection is basically providing the objects that an object needs (here the EmployeeService ) instead of having it construct them itself. I’m going to use constructor injection in this application and let the unity to create new instance of EmployeeService for EmployeeController. There we need to add constructor to our EmployeeControllerwith parameter as below.
using Services;
namespace DIWithUnityMVC.Controllers
{
public class EmployeeController : Controller
{
private readonly IEmployeeService employeeService;
//Constructor Injection to inject the dependency at runtime
public EmployeeController(IEmployeeService _employeeService)
{
employeeService = _employeeService;
}
//Get : EmployeeDetails
public ActionResult Index()
{
return View(employeeService.GetEmployeeDetails());
}
}
}
You can see that i can not create any object of EmployeeService inside the controller.So how employee object available in controller. here DI (Dependency Injection) play vital role and i have use Constructor injection to instantiate the employee class.
Next I will add the view to show the employee details as per below:

Enter a caption
After adding view successfully,your cshtml file will look likes below:
Snippet
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.EmployeeName)
@Html.DisplayNameFor(model => model.HomeTown)
@Html.DisplayNameFor(model => model.DepartmentId)
@foreach (var item in Model) {
@Html.DisplayFor(modelItem => item.EmployeeName)
@Html.DisplayFor(modelItem => item.HomeTown)
@Html.DisplayFor(modelItem => item.DepartmentId)
@Html.ActionLink("Edit", "Edit", new { id=item.EmployeeId }) |
@Html.ActionLink("Details", "Details", new { id=item.EmployeeId }) |
@Html.ActionLink("Delete", "Delete", new { id=item.EmployeeId })
}
It’s done, you can run your application and try /Institution/Index. You should get following output.

6. Move Unity Configuration to Separate File
We can move unity configuration to separate file which enable us to do modifications without recompiling existing application. We can do this by adding config section to web.config file as below.
Updated Unity.Config:
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<IEmployeeService, EmployeeService>();
container.LoadConfiguration();
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
}
}
Modified Web.Config:
<configSections>
<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" />
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<unity configSource="unity.config" />
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-DIWithUnityMVC-20160724093832.mdf;Initial Catalog=aspnet-DIWithUnityMVC-20160724093832;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
New Unity.Config:
Snippet
<?xml version="1.0" encoding="utf-8" ?>
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
<container>
<register type="Services.IEmployeeService, Services" mapTo="Services.EmployeeService, Services" />
</container>
</unity>