Global.asax.cs and Static variable

11,554

You could use an application variable:

public static IList<MyData> Data {
    get
    {
        if (Application["MyIListData"] != null)
            return (IList<MyData>)Application["MyIListData"];
        else
            return new IList<MyData>();
    }
    set
    {
        Application["MyIListData"] = value;    
    }
} 

protected void Application_Start(object sender, EventArgs e)
{
    Data = Load();
}

Not really much different in actual implementation except that now it's available globally through that variable name as an application variable.

Share:
11,554
Martin
Author by

Martin

Updated on June 04, 2022

Comments

  • Martin
    Martin almost 2 years

    In a WCF Service, I need to create a variable which should be accessible anytime from anywhere. All methods of my service need to have access to that data and I can load it only once. So I though about using a static variable in the Global.asax.cs. However I am not sure to understand what is going to be the scope of that variable. Is that data is going to be used for all the requests? My understanding is that it should because the same static variable should be used across the App Domain. Is that correct?

    public static IList<MyData> Data { get; set; } 
    private static IList<MyData> Load() 
    {
        return Big data struct from DB.
    }
    
    protected void Application_Start(object sender, EventArgs e)
    {
        Data = Load();
    }
    

    Finally, is there a better way to achieve that? I am not a big fan of static variable...

  • codymanix
    codymanix almost 13 years
    Personally, I find global untyped Hashtables like Application is worse then a single typed object. Is Application data shared accross app domain, at least?
  • Joel Etherton
    Joel Etherton almost 13 years
    @codymanix: Yah, this makes the variable universally available across the entire AppDomain. It's not my favorite method of storing this type of information, but for aggregate appdomain specific information it's a good common mechanism to use. It's not the method I use to accomplish this task, but it does work.