Search code examples
c#asp.net-mvc-3httpcontext

Why are my HttpApplication instance variables null?


I have a MVC3 application to which I've added a couple of simple cache variables as a property. I add my data in Application_Start and then later in a controller try to cast the HttpContext.ApplicationInstance back to my type to access it. But, the property is always null. Here's an example:

EDITED TO WORKING EXAMPLE

public interface IMyMvcApp
{
    Hashtable Cache {get;set;}
}


public class MvcApplication: HttpApplication, IMyMvcApp
{

    public Hashtable Cache 
    {
        get { return Context.Cache["MyStuff"] as Hashtable; }
        set { Context.Cache["MyStuff"] = value}
    }

    public void Application_Start()
    {
        Cache = new Hashtable();
        Cache.Add("key", new object());
    }
}

public class AController : Controller
{
    protected override void OnActionExecuting(ActionExecutingContext context)
    {
        var myApp = context.HttpContext.ApplicationInstance as IMyMvcApp;

        Assert.IsNotNull(myApp.Cache);
    }
}

Solution

  • There are multiple instances of the application created by the framework. To verify this add an empty constructor and put a breakpoint in it. You will see that this constructor will be hit multiple times whereas the Application_Start only once.

    So instead of reinventing wheels you should use the Cache object that's already built into the framework:

    protected void Application_Start()
    {
        ...
        Context.Cache["key"] = new object();
    }
    

    and then:

    protected override void OnActionExecuting(ActionExecutingContext context)
    {
        var value = context.HttpContext.Cache["key"];
    }