Click here to Skip to main content
15,860,972 members
Articles / .NET / .NET4.5
Tip/Trick

Configure Unity for ASP.NET MVC - Up and Running

Rate me:
Please Sign up or sign in to vote.
4.60/5 (3 votes)
24 May 2014CPOL2 min read 14.1K   6  
Easy way to understand configuring unity for an ASP.NET MVC application

Introduction

This tip explains how unity container (IOC) can be configured and used easily for an ASP.NET MVC application.

Background

Unity is a framework a.k.a. IOC container from Microsoft patterns and practises team used to incorporate Dependency Injection (DI) , when I say DI it means it's a way of injecting dependencies like Logging, exception handling or other Cross cutting utility services to our application, diving into DI or IOC is out of scope for this article .

Using the Code

In order to get started with unity, first and foremost download it using nuget command in VS2012/VS2010 package manager console shown in the below figure. It installs the appropriate unity based on the ASP.NET MVC version used.

Image 1

This command installs unity related libraries and files to your application.

It also creates a Bootstrapper.cs file in the application root (figure below).

Image 2

This bootStrapper class is used to initialize the unity container for Dependency Injection shown in the figure below. Explaining what happens down the hood is out of scope of this article .

Image 3

Now let us create an ILogger interface and concrete class EventLogger, ILogger is a dependency of course.

C++
// ILogger and Concrete logger implementation 

Image 4

Now go to Bootstrapper.cs file created earlier and uncomment the line container.RegisterType as shown in the below figure .

Image 5

Now last but not the least, go to Global.asax and in the application_Start method, call the BootStrapper.Initialise() method as shown in the figure (last line of code).

Image 6

Hurry! We have successfully set up Unity in our MVC application.

To test it, go to any of the controller class and create a constructor and pass the ILogger Interface like this shown below in the figure.

Image 7

Ilogger is injected (DI) in the Home controller constructor via constructor injection . which is taken care by IOC, i.e., unity .

Points of Interest

I tried to make this simple and sweet rather confusing, some tweaking the readers have to make themselves to get things working. :)

Happy coding!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
India India
Computer geek very much interested in learning and adopting latest and cutting edge technologies .

Expertise in asp.net,c#,WCF,web services,Jquery,MVC ,TTD's and design principles and patterns applying SOLID

Designation - Architect
This is a Organisation

9 members

Comments and Discussions

 
-- There are no messages in this forum --