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.

5 responses to “Resolving Dependencies in ASP.NET MVC 5 using Unity Container”

  1. […] Resolving Dependencies in ASP.NET MVC 5 using Unity Container (Dhananjay Kumar) […]

  2. […] Resolving Dependencies in ASP.NET MVC 5 using Unity Container (Dhananjay Kumar) […]

  3. Nice and easy. Thank you!

  4. Nice article, I found following post with sample code and screen-shots.
    MVC 5 with Unity for Dependency Injection

  5. Nice article. helped me lot. great job Dhananjay Kumar

Leave a comment

Create a website or blog at WordPress.com