Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Configure Unity for ASP.NET MVC - Up and Running

0.00/5 (No votes)
24 May 2014 1  
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.

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!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here