Resolving Dependencies in ASP.NET MVC 5 using Unity Container

In this post, I will show you how to use Unity Container in ASP.NET MVC 5 application. This post may be handy for you because the way Unity was used in MVC 4 has been changed in MVC 5. Assuming you already have ASP.NET MVC 5 application, you can start using Unity Container using Nuget. Right click on project and from context menu click on Manage Nuget Packages and search for Unity.mvc5. Click to install Unity.mvc5 package in ASP.NET MVC application.

clip_image002

In App_Start folder you will find UnityConfig.cs. UnityConfig is a static class with one static method RegisterComponents. In this method you need to register dependency. For example ASP.NET MVC 5 application I am working on, got MovieRepository class depended on IMovieRepository. You need to instruct unity that IMovieRepository should resolve to MovieRepository. You can do this by registering type in Unity Container. [See image below]

clip_image004

If you have more than one dependencies all should get registered to container in RegisterComponents function. After registering all dependencies call RegisterComponents function in Application_Start() of Global.asax.cs . This can be done as shown below,

clip_image006

Note:

In earlier version of ASP.NET MVC and UNITY, you might have seen BootStrapper.start(). In MVC 5 it has been changed to UnityConfig.RegisterComponents()

In Controller class now I can inject dependency simply as below,

clip_image008

This is what all you need to do to resolve dependency using Unity Container in ASP.NET MVC application. In further posts I will discuss how to use other IOC containers like Structuremap, Windsor etc.

Happy Coding.

Unity Framework

Objective

This tutorial will explain step by step explanation of how to use UNITY Framework in code. UNITY Framework is a framework of Microsoft to achieve Inversion of Control Design Pattern.

To know more about, what is Inversion of Control and Dependency Pattern design pattern read my previous article Click here.

Two very good articles on same topic by Mr ShivPrasad Koirala could be read at following links

Design pattern Inversion of Control and DI and IOC

How to use UNITY Container

Step 1

Download UNITY application block from Here

Step 2

Create New Project and Console application.

Step 3

Add reference to

Microsoft.Practices.Unity ,Microsoft.Practices.Unity.Configuration;


Step 4

Right click on project and add new item and then select interface. Give name of the interface as IPlayer.


Type below code in IPlayer.cs . This interface will registered as type to Unity Container.

IPlayer.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace UnityTesting

{


public
interface
IPlayer

{


string PlayerName

{


get;


set;

}


string TeamName

{


get;


set;

}


void DisplayDetails();

}

}

Step 5

Right click on project and add new class. Give name of the class as Player.cs

Note: Player class is implementing IPlayer interface.


Type below code in Player.cs.

Player.cs

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace UnityTesting

{


public
class
Player:IPlayer

{


public Player()

{

}


string name;


string teamName;


public
string PlayerName

{


get

{


return name;

}


set

{

name = value;

}

}


public
string TeamName

{


get

{


return teamName;

}


set

{

teamName = value;

}

}


public
void DisplayDetails()

{


Console.WriteLine(“Player Name = \t” + name + ” \tPlayer Team Name = \t” + teamName);


//Console.WriteLine(p.PlayerName);

}

}

}

Step 6

 

Factory Class

: This is a class, which is responsible for

  1. Setting up the Unity Container. (Task A)
  2. Registering interface as a type to the container. (Task B)
  3. Returning instance of the registered type or Resolve an object by the type. ( Task C)

Add a new class in project by right clicking and give name of the class as Factory. Factory is name here; give any name as per desire.


In Factory.cs add namespaces

using Microsoft.Practices.Unity;

using Microsoft.Practices.Unity.Configuration;

Task A:


Set Up Container

To set up container, create instance of IUnityContainer class.


IUnityContainer _container = new
UnityContainer();

The above code will create an instance of container class.

Task B: Register interface as a type

 

  1. RegisterType method of container class is used to register a type into the container.
  2. At the appropriate time, the container will build an instance of the type which is specified.
  3. The lifetime of the object it builds will correspond to the life time specified in the parameters of the method.
  4. If lifetime is not specified then the type will registered for a transient lifetime, which means that a new instance will be created on each call to Resolve. ( It is method , which will be discussed later)
  5. This method is overloaded with 8 different parameters.

 


 

How to register a type?

 

_container.RegisterType(typeof(IPlayer), typof(Player));

Task C: Resolve an Object by the type

 

  1. To resolve an objcet by type , Resolve method will be used.
  2. To retrieve object instances from the container.
  3. When this method is used without specifying a value for the optional name property, the method returns the object registered with the default mapping.
  4. This method is overloaded with two types of arguments. One takes only type and other argument takes type as well as string name of the registered type.


How to resolve instance of registered type?

 

IPlayer obj = _container.Resolve<IPlayer>();

If exact return type of instance is known then that could be also applied like

Player obj1 = _container.Resolve<Player>();

Putting altogether the Factory class.

Factory.cs

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using Microsoft.Practices.Unity;

using Microsoft.Practices.Unity.Configuration;

namespace UnityTesting

{


public
class
Factory

{


static
public
IPlayer CreateInstance()

{


IUnityContainer _container = new
UnityContainer();

_container.RegisterType(typeof(IPlayer), typeof(Player));


IPlayer obj = _container.Resolve<IPlayer>();


return obj;

}

}

}

Explanation:

 

CreateInstance() is a static method. This method will return instance of type registered to the container.

Step 7

Now solution explorer should look like as below


Step 8

Click on Program.cs and paste below code

Program.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using Microsoft.Practices.Unity;

using Microsoft.Practices.Unity.Configuration;

using System.Configuration;

namespace UnityTesting

{


class
Program

{


static
void Main(string[] args)

{


IPlayer obj = Factory.CreateInstance();

obj.PlayerName = ” Sachin Tendulkar “;

obj.TeamName = ” India “;

obj.DisplayDetails();


IPlayer obj1 = Factory.CreateInstance();

obj.PlayerName = ” Shane warne”;

obj.TeamName = ” Australia “;

obj.DisplayDetails();


Console.Read();

}

}

}

Explanation:

IPlayer obj = Factory.CreateInstance();

This code is used to create a instance if type Player using Unity Container.

obj.PlayerName = ” Sachin Tendulkar “;

obj.TeamName = ” India “;

obj.DisplayDetails();

Now properties and methods of class being called using instance of the class.

Here Each time calling Resolve method is returning an instance of registered type , because time line is variant and not specified.

Output


Conclusion

This article has explained , How yo use UNITY Container using the code .

 Future scope

 In next article, I shall explain how to


  1. To register an existing object instance as an externally controlled instance
  2. To register an existing object as a singleton instance

 Happy Coding .

Unity Frame Work in ASP.Net MVC Application

Objective

This article will explain step by step that how to inject dependency using UNITY framework in ASP.Net MVC Application

Step 1

Create a MVC application

Step 2

Add Unity references to the MVC application.


Step 3

Idea here is to create a custom controller factory. This custom controller factory will create the controller and inject the dependencies in that. Add a class to the project. Feel free to give any name; here name of the class is CustomUnityControllerFactory.


Extend this CustomUnityControllerFactory class from DefaultControllerFactory class.

Create reference of IUnityContainer. Don’t forget to add include namespace Unity.

Create the constructor for CustomUnityControllerFactory and pass reference of Unity Container in that.

Override GetControllerInstance of DefaultControllerFactory. Here we will pass type of the controller , which we are going to create. In parameter of overrideen function we are passing type of the controller to be instanciated.

So the complete CustomUnityControllerFactory class will look like below.

CustomUnityControllerFactory.cs

Step 4:

 Now we need to do something at start up of the application. For that open Global. asax file. We need to modify Application.Start() method.

  1. Create instance of IUnityContainer.
  2. Create instance of CustomUnityControllerFactory and pass instance of unity container in that.
  3. Set the CustomUnityControllerFactory as the default controller factory to be used. For this call Current method on ControllerBuilder and pass instance of CustomUnityControllerFactory in that. (see below code in blue)

  1. Compile the application.

Step 5

Now it is time to check that, how Custom Unity Container Factory is working. To test that, we will create a service interface and concrete service class in Model.

  1. Right click on Model and add an interface

    Interface contains the below code.

  1. Right click on Model and add a class and implement the Message() method.

     

    Class contains the below code

                                                                                                                                                                                            

Step 6

Go to Application_Start() and register the type 

So, now the complete code at Application Start () will look like

 Step 7
Now put a breakpoint at constructor of HomeController and run the application. We could see while debugging that dependency has been injected.


Now, you can see that dependency has been injected. Now normal routing will process. For Routing and other details of MVP read my articles here.

Conclusion:

 I showed how to inject dependency using Unity in MVC application.