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