find a location for property in a new city

Wednesday, 15 September 2010

Using Application State as early as possible in ASP.NET MVC

I'm working on a new website that will run off the same architecture as To distinguish one site from the other I am using a variable stored in ApplicationState. However I was running into problems when trying to access this variable.

The problem was that I was setting the Application variable in Application_Start() of Global.asax. I was accessing this variable in the contructor of my base Controller (that all my Controllers inherit from).

This was too early. Not too early for the Application_Start() event, obviously. Just too early to be able to access it I assume.

So how early can I access ApplicationState?

I found I could access it without problem on the Initialize method of my BaseController:
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
    //only here is the application state finally ready to be set
    SiteID = (int)requestContext.HttpContext.Application["SiteID"];

Problem is I really want to be able to access it during construction of my BaseController though since I will be implementing DI shortly. So in the end I used AppSettings in the config instead which can be accessed in the constructor. Still, this will still be useful I'm sure.

Follow britishdev on Twitter