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.
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]
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,
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,
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.
Leave a Reply