Reputation: 16430
Inside controller action you can:
MvcApplication app = this.HttpContext.ApplicationInstance as MvcApplication;
But this.HttpContext.ApplicationInstance
only holds the superclass, not the derived class declared in Global.asax. Therefore any instance properties you declared there, are null;
Is there a way around this? Shouldn't there be a way to access the derived app class?
I'd like to have instances (of my helper classes), stored as instance properties inside the application instance, rather than having them as static classes.
Or do static helpers, hold no drawbacks?
Upvotes: 3
Views: 3401
Reputation: 16430
Late answer (but for anyone in need of assistance).
I had this issue as well.
I think you can use the Application["myKey"] array, to set some values. Sure they aren't instance properties, but you can set a dependency injection container (like unity, who recommends this option in their code sample) , then access it from your controller with Application["myKey"].
From http://msdn.microsoft.com/en-us/library/ms178473%28VS.80%29.aspx
You should set only static data during application start. Do not set any instance data because it will be available only to the first instance of the HttpApplication class that is created.
Upvotes: 1
Reputation: 39956
There is no harm in using single static class, because your code becomes portable to non web project as well.
Ideally, instead of static properties, you can create MyApp class and wrap all app specific global data and other utility methods. And either you can create a static instance property and store instance of MyApp in HttpContext.Current.Application which is globally accessible in each request.
I think you are not aware that HttpApplication class is reused, and I suspect that your some handler is cleaning the properties.
Upvotes: 0
Reputation: 6942
There is a way around this and you've already written it:
MvcApplication app = this.HttpContext.ApplicationInstance as MvcApplication;
If you don't like that, try changing your MvcApplication
class to:
public class MvcApplication : HttpApplication
{
public static MvcApplication Instance
{
get
{
// Current could be null, depending on the caller
return HttpContext.Current != null
? HttpContext.Current.ApplicationInstance
: null;
}
}
}
Then you can access your application as MvcApplication.Instance
. Be cautious that Instance
is not null.
Upvotes: 4