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.

Published by

Dhananjay Kumar

Dhananjay Kumar is Developer Evangelist for Infragistics. He is a 8 times Microsoft MVP and well respected Developer Advocate in India.He is the author of 900+ Blog Posts, and can often be found speaking around India at conferences and hosting free workshops for programmers across the country. So far, he has hosted 60 free workshops on various topics like JavaScript, Angular, WCF, ASP.NET MVC, C#, Azure etc. Follow him on twitter @debug_mode for all the updates about his blog posts and workshops. You can send him email at debugmode [at] outlook [dot] com

5 thoughts on “Resolving Dependencies in ASP.NET MVC 5 using Unity Container”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s