Skip Navigation LinksHome > Categories > Code from a Category

How To Use Unity Container In ASP.NET

User Name: tippu
Name: King SheZ
Contact Me:
Home Page:
7 years of enterprise application development, so far in my career i have worked on enterprise web applications with millions of users,i have also worked on many integrations between applications, i h... [More]
Viewed Times: 4244
Add Date: 08/03/2011
Today’s post will explain how to include Unity container in ASP.NET web applications. The details I write here are based on David Hayden’s screen cast and therefore the credit is for David Hayden.

Another good example of how to use Unity container through WCF service can be found in this post.

Building The Container

The first thing to do is to build the Unity container. We would like to have a persistent container that hold it’s state during the running of the application. The right place to put the is as part of the Global.asax file as a property of the current running application. First build an interface for the container property:

After the building of the interface implement it in the Global class in the Global.asax file:

In the implementation you hold a static container variable which will be available in the web application through the interface we build. In the BuildContainer method we do all the work of registering types and instances to the Unity container. It can be done by code or by configuration this decision is yours.

How To Inject Dependencies

After you set up your container it’s time to use it. It is done by building a base page for all the pages in your application. The injection of dependencies should be done very early in the page life cycle and therefore implemented in the OnPreInit event. The base page class can look like:

All the checks in the InjectDependencies method are a guarantee that we have a Unity container. The only interesting part here is the BuildUp method in the end of the method. The BuildUp method will ensure that the injection will happen as required.

Example Of Concrete Page

After building the base page the only thing to do next is to implement the other pages and inheriting from the base page. The next example shows how to use the previous BasePage class:


To sum up the post, I showed an example that was suggested by David Hayden of how to use Unity in ASP.NET application. This is a very simple example that will help you to get started with Unity in your web applications. I suggest to see David Hayden’s screen cast for more details.

Post a Comment

Name: (Optional)
Email: (Optional, you can get an email if somebody replys your comments)*
Email me if somebody respons my comment below:
Enter Text
as Below:
(case insensitive, if hard to read, click the "get a new one" button)
* Your email address will not be shared with any third parties for any reason.
** Maximum 1000 charactors.