的Global.asax.cs和静态变量 [英] Global.asax.cs and Static variable

查看:276
本文介绍了的Global.asax.cs和静态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在WCF服务,我需要创建这应该是访问随时随地的变量。我服务的所有方法都需要访问这些数据,我只能一次加载它。所以,我虽然有关在Global.asax.cs中使用静态变量。但是我不知道理解什么将是该变量的范围。的是,数据将被用于所有的请求?我的理解是,它应该因为同样的静态变量应该在整个应用程序域使用。 ?那是正确的。

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...

推荐答案

您可以使用应用程序变量的忠实粉丝:

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.

这篇关于的Global.asax.cs和静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆