Global.asax.cs and static variable

In the WCF service, I need to create a variable that should be available anytime from anywhere. All methods of my service should have access to this data, and I can download them only once. So I though about using a static variable in Global.asax.cs. However, I'm not sure to understand what will be the scope of this variable. Will this data be used for all queries? I understand that this should be due to the fact that the same static variable must be used in the application domain. It is right?

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 this? I am not a big fan of static variable ...

+6
source share
3 answers

You can use the 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(); } 

In a real implementation, it’s not very different, except that it is now accessible globally through this variable name as an application variable.

+5
source

Yes, the static variable is valid / visible from all threads / sessions in your application .

AFAIK, static variables are not shared between AppDomains . To complete this task, you can look in this example .

You do not need the global variable, but you need something accessible from anyone and everywhere, do you see a contradiction? Any kind of singleton is just a global variable. But in your case, this seems to be the best solution. You just have to make sure your global object is immutable and thread safe .

0
source

I would use the Singleton template to store your "application wide" variable. It is static, will be allocated after the first use and is available for the duration of your application. I also think this is much better than using an untyped HashTable application such as an application. For me, Application storage is a relic from ASP and is no longer useful in an object-oriented world.

Be careful that a static variable is initialized only once, because each request for a web request / service is executed in its own thread.

Similarly, you can load data the first time you use it and access it everywhere with MyData.Data:

 public class MyData { private static IList<MyData> _data { get; set; } public static IList<MyData> Data { get { if (_data == null) _data = load Big data struct from DB. return _data; } } } 

An event would be better initialization in a static constructor, because then the call would be thread safe.

0
source

Source: https://habr.com/ru/post/889136/


All Articles