Click here to Skip to main content
13,147,050 members (61,690 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


6 bookmarked
Posted 24 May 2014

Configure Unity for ASP.NET MVC - Up and Running

, 24 May 2014
Rate this:
Please Sign up or sign in to vote.
Easy way to understand configuring unity for an ASP.NET MVC application


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


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.

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

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

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 .

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

// ILogger and Concrete logger implementation 

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

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).

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.

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!


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


About the Author

India India
This member doesn't quite have enough reputation to be able to display their biography and homepage.
Group type: Organisation

9 members

You may also be interested in...

Comments and Discussions

-- There are no messages in this forum --
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.170915.1 | Last Updated 24 May 2014
Article Copyright 2014 by imsauravroy
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid