In general, it is bad practice to access objects using a static field in asp.net applications, as this can lead to errors that are hardly detected and reproduced: this is especially true for objects that are not subject to a constant / non-thread like a dictionary.
I assume that you want to cache some database data in memory to avoid excessive SQL queries. For this purpose, we recommend using standard asp.net caching:
public IDictionary GetDict() { var dict = HttpRuntime.Cache.Get("uniqueCacheKey") as IDictionary; if (pvtData==null) { dict = doLoadDictionaryFromDB(); // your code that loads data from DB HttpRuntime.Cache.Add(cacheKey, dict, null, Cache.NoAbsoluteExpiration, new TimeSpan(0,5,0), // cache at least for 5 minutes after last access CacheItemPriority.Normal, null); } return dict; }
This approach allows you to choose the appropriate expiration policy (without having to reinvent the wheel with a static dictionary).
If you still want to use a static dictionary, you can put it at the top of the application (global.asax):
void Application_Start(object sender, EventArgs e) {
source share