IUnityContainerAccessor must use a static container instance

I found an interesting problem this morning when my ASP.NET MVC application mysteriously broke after adding an HttpModule in the web.config. Here’s the problem code:

public class MvcApplication : HttpApplication, IUnityContainerAccessor
{
    IUnityContainer container;

    public IUnityContainer Container
    {
        get { return container; }
    }

    public void Application_Start()
    {
        this.container = new UnityContainer();

        // this.container.RegisterTypes etc
    }

The container was being configured fine in Application_Start, but then UnityControllerFactory would throw “The container seems to be unavailable in your HttpApplication subclass” exceptions every time you tried to load a page — this.container was somehow null again.

After doing a little digging and finding this article where someone had the same problem with Winsdor, it seems ASP.NET will create multiple HttpApplication instances when parallel requests are received. However, Application_Start only gets called once, so anything you would like to share between multiple instances (e.g. your IoC container) must be static:

public class MvcApplication : HttpApplication, IUnityContainerAccessor
{
    static IUnityContainer container; // good

    IUnityContainer container; // bad, not shared between HttpApplication instances

    public IUnityContainer Container
    {
        get { return container; }
    }
April 17, 2009

2 Comments

Lycia Andrews on June 15, 2009 at 12:22 am.

Whats the good word Mate? Very Good blog here mate…You australian?

Richard on June 15, 2009 at 9:00 am.

Kiwi :)

Leave Your Comment

Your email will not be published or shared. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>