Unity in ASP.NET MVC 4 and ASP.NET Web API

Published on
12,519 Points
1 Endorsement
Last Modified:
Thought this will help someone who wants to learn Unity framework in ASP.NET MVC 4 and ASP.NET Web API. Since the controllers are called directly by the MVC framework and as soon as you start introduce Repository Pattern in your project , unity framework will be very handy create dependent objects in your MVC Controller or Web API Controller.  By Coding to Interfaces enables us to test the projects easily by any mocking frameworks.

Let us see how to use UNITY in MVC 4 Controllers.

There are 3 things should be followed while using Dependency Injection. Design, Register and Resolve.

1. Design

Simplest of 3 steps I guess. Have the controller constructor takes a repository Interface like this.

public class TeamsController : Controller
        private readonly ITeamRepository teamRepository;

        public TeamsController(ITeamRepository teamRepository)
	this.teamRepository = teamRepository;

Open in new window

2. Register

How we are going to register the above dependency injection so that when the controller is called the unity jumps in creates the dependent objects.

Registration can be done in two ways. Using the config.file and doing in the Code.

2.1 Let’s see how to register by web.config file.

2.1.1. Place below secion inside(configuration -> configSections)
<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" />

2.1.2. Paste below <unity> element inside configuration section of web.cofig. Below I’m registering ITeamRepository so that whenever this object is passed in the constructor, unity framework will create concrete object which is in "mapto".We group these registration inside containers.

 <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
    <alias alias="Singleton" type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager, Microsoft.Practices.Unity"/>
    <alias alias="Transient" type="Microsoft.Practices.Unity.TransientLifetimeManager, Microsoft.Practices.Unity"/>

    <alias alias="ITeamRepository" type="PrecisionPrinting.OneFlow.WebAPI.Models.ITeamRepository, PrecisionPrinting.OneFlow.WebAPI" />
    <alias alias="TeamRepository" type="PrecisionPrinting.OneFlow.WebAPI.Models.TeamRepository, PrecisionPrinting.OneFlow.WebAPI" />
        <register type="ITeamRepository" mapTo="TeamRepository" name="teamRepository" />
        <register type="PrecisionPrinting.OneFlow.WebAPI.Controllers.TeamsController, PrecisionPrinting.OneFlow.WebAPI">
            <lifetime type="Transient" />
                <param name="teamRepository" >
                  <dependency type="TeamRepository"/>

Open in new window

2.2. how to register in the code.

//Create unitycontainer
IDependencyResolver ioc = new UnityDependencyResolver();
 ioc.Register<ITeamRepository>(new TeamRepository());

Open in new window

3. Resolve.

Use the container to get the instances of the controller. Please see the attached controllerfactory file.
Finally, we have to have below lines in your Application_Start method of global.asax.cs file. We can wrap below lines inside a static class.

//Mandatory line
IDependencyResolver ioc = new UnityDependencyResolver();
//below line is required if you don't use web.config file to register.
ioc.Register<ITeamRepository>(new TeamRepository());
////below line should be added if you want Unity in WEB API controllers.
ControllerBuilder.Current.SetControllerFactory(new ControllerFactory(ioc));
//below line should be added if you want Unity in WEB API controllers.
 GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver();  

Open in new window

Some details of the attached files. Add the attached files to your solution.

This class implements "IDependencyResolver"  which are required for MVC 4 controllers Dependency Injection. It also implements IDependencyScope, System.Web.Http.Dependencies.IDependencyResolver which are required for WEB API Dependency injection. Please remove the interfaces accordingly if you don't any of them.
Also in the method, " UnityDependencyResolver(IUnityContainer container)" comment last twp lines if you are registering in the code instead of web.config.

This is a custom class which can extended as required

Let’s us see how to use Unity in WEB API Controllers.

Here also we have to Design, Register api controller (either in web.config or in code) and Resolve. It is the same process as above except few more changes.

By Implementing IDependencyScope, System.Web.Http.Dependencies.IDependencyResolver in UnityDependencyResolver class

we can use the same class to support both MVC 4 Controllers and We b API Controllers

Tell the framework to use our Resolver for dependency injection by including the line below in application_start() event.
GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver();

Open in new window

Enjoy this complimentary article view.

Get unlimited access to our entire library of technical procedures, guides, and tutorials written by certified industry professionals.

Get 7 days free
Click here to view the full article

Using this article for work? Experts Exchange can benefit your whole team.

Learn More
Experts Exchange is a tech solutions provider where users receive personalized tech help from vetted certified professionals. These industry professionals also write and publish relevant articles on our site.
Ask questions about what you read
If you have a question about something within an article, you can receive help directly from the article author. Experts Exchange article authors are available to answer questions and further the discussion.
Learn from the best.