What is the best approach to global variables in ASP.Net applications?

For my global variables and data, I am in a dilemma as to whether to use HttpApplicationState or static variables. What is the best approach?

This document states that you should use static variables for httpapplicationstate: http://support.microsoft.com/default.aspx?scid=kb;en-us;Q312607

However, one thing I like about HttpApplicationState (and System.Web.Caching.Cache) is that you can easily list the entries and choose which items to delete (for this purpose I created a global CacheManager.axd), at that time as I don’t think that there is a simple way with static variables (and even then it’s not clear what to do to “reinitialize” them) without processing the application pool.

Any suggestions for a neat, universal way to process and manage global objects?

Thanks Mark.

+4
source share
2 answers

Your instincts are true. Use System.Web.Caching. Built-in cache management takes care of all the heavy upgrades regarding memory allocation and expiration of obsolete or low priority objects.

Be sure to use the naming convention for cache keys, which makes sense in the future. If you start relying heavily on caching, you will need to be able to target / filter different cache keys by name.

+1
source

As a general practice, it is useful to try to avoid global status in web applications whenever possible. . ASP.NET is a multi-threaded environment in which multiple requests can be served in parallel. If your global state is not immutable (read-only), you will have to solve the problems that govern the general mutable state.

If your general state is immutable, and you do not need to list it, then I do not see problems with static variables.

If your shared state is mutable / mutable, then you probably want to create an abstraction on top of which underlyig mechanism you prefer to store data to ensure access and change of this general state is consistent and meets the expectations of the code that consumes it. I would probably use the system cache in such a design, just to be able to use the expiration and dependency functions built into the cache service (if necessary).

0
source

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


All Articles