DCSIMG
How To Use Unity Container In ASP.NET - Gil Fink's Blog

Gil Fink's Blog

Fink about IT

News

Microsoft MVP

My Facebook Profile My Twitter Profile My Linkedin Profile

Locations of visitors to this page

Creative Commons License

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.
© Copyright 2013 Gil Fink

Hebrew Articles

Index Pages

My OSS Projects

English Articles

How To Use Unity Container In ASP.NET

How To Use Unity Container In ASP.NET

Today’s post will explain how to include Unity container  Unity Application Block
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:

    public interface IContainerAccessor

    {

        IUnityContainer Container { get; }

    }

 

 

 

 

 

 

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

    public class Global : HttpApplication, IContainerAccessor

    {

        #region Members

        private static IUnityContainer _container;

        #endregion

        #region Properties

        /// <summary>

        /// The Unity container for the current application

        /// </summary>

        public static IUnityContainer Container

        {

            get

            {

                return _container;

            }

            set

            {

                _container = value;

            }

        }

        #endregion

        #region IContainerAccessor Members

        /// <summary>

        /// Returns the Unity container of the application

        /// </summary>

        IUnityContainer IContainerAccessor.Container

        {

            get

            {

                return Container;

            }

        }

        #endregion

        #region Application Events

        protected void Application_Start(object sender, EventArgs e)

        {

            BuildContainer();

        }

        protected void Application_End(object sender, EventArgs e)

        {

            CleanUp();

        }

        #endregion

        #region Methods

        private static void BuildContainer()

        {

            IUnityContainer container = new UnityContainer();

            // Register the relevant types for the

            // container here through classes or configuration

            // register the container in the container property

            Container = container;

        }

        private static void CleanUp()

        {

            if (Container != null)

            {

                Container.Dispose();

            }

        }

        #endregion

    }

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:

    public abstract class BasePage<T> : Page where T : class

    {

        protected override void  OnPreInit(EventArgs e)

        {

            InjectDependencies();

            base.OnPreInit(e);

        }

        protected virtual void InjectDependencies()

        {

            var context = HttpContext.Current;

            if (context == null)

            {

                return;

            }

            var accessor = context.ApplicationInstance as IContainerAccessor;

            if (accessor == null)

            {

                return;

            }

            var container = accessor.Container;

            if (container == null)

            {

                throw new InvalidOperationException("No Unity container found");

            }

            container.BuildUp(this as T);

        }

    }

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:

    public partial class _Default : BasePage<_Default>

    {

        #region Properties

        [Dependency]

        private ILogger Logger { set; get; }

        #endregion

        #region Page Events

        protected void Page_Load(object sender, EventArgs e)

        {

            Logger.Log("Something");

        }

        #endregion

    }

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

Comments

DotNetKicks.com said:

You've been kicked (a good thing) - Trackback from DotNetKicks.com

# July 1, 2008 8:45 PM

Unity - Dependency Injection and Inversion of Control Container | Tea Break said:

Pingback from  Unity - Dependency Injection and Inversion of Control Container | Tea Break

# September 8, 2008 12:21 PM

Gil Fink on .Net said:

How To Use Unity Container In ASP.NET MVC Framework In the past I wrote the post How To Use Unity Container

# February 8, 2009 3:15 PM

Unity ??? Dependency Injection and Inversion of Control??Container « It Works On My Machine said:

Pingback from  Unity ??? Dependency Injection and Inversion of Control??Container &laquo; It Works On My Machine

# November 7, 2010 7:17 PM

Design Patterns : Using Unity for Dependency Injection | Samuel {n} Mensah said:

Pingback from  Design Patterns : Using Unity for Dependency Injection | Samuel {n} Mensah

# November 27, 2012 7:41 PM