1

Recently I have been busy writing an MVC 4 Website and I need to hold some values across all the sessions so I deciede to use the "Application State" object. Because the MvcApplication class which rests inside the Global.asax.cs is of type HttpApplication and it is guaranteed to be initialized at the Application Start, I deceided it would be a good reference for the "Application State" object so I created a Singleton inside this class like this:

public class MvcApplication : HttpApplication
{
    public static HttpApplicationState Singleton;

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        AuthConfig.RegisterAuth();

        Singleton = this.Application; //<== Here it is!
    }

    protected void Application_Error(object sender, EventArgs e)
    {

    }
}

So I can now access this object like this:

MvcApplication.Singleton

Because I want my code to be standard and avoid non-standard code, I want to make sure if it is a good way to do such thing or not.

Thanks in advance for you attention.

Rojan Gh.
  • 707
  • 1
  • 6
  • 25

0 Answers0