Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.net page lifecycle-specific global variable?

Tags:

c#

asp.net

vb.net

Surely it must be a common problem but I can't find an easy way to do this.

Is there a way to share a global variable (say a class which is expensive to instantiate) through the life cycle of an asp.net webform, without having to pass the handle to every single component of the page?

If I just create a static variable, it will be accessible by all threads in the app domain (problem: my class is not thread safe), and it will be hard to ensure that every page works on a recent copy (I want to cache the class through every step of the life cycle of the page, but I want a new instance every time a new page is called).

The alternative is to pass a handle through each control in the page, but between the master page, the page itself, and all the user controls, it makes the code quite hairy.

I was wondering if there wasn't an elegant solution to store a class in some place which is accessible only to the thread executing this particular page (including all sub user controls)?

Any suggestion welcome! Thanks Charles

like image 886
Charles Avatar asked Aug 04 '12 16:08

Charles


Video Answer


1 Answers

There is a simple answer: the Items container. It is available for the lifetime of a single request and then it is automatically destroyed. You can wrap it in a property to have what you want:

 public class Foo {

   const string SOMEKEY = "_somekey";

   public static string SingleRequestVariable
   {
      get
      {
          return (string)HttpContext.Current.Items[SOMEKEY];   
      }
      set
      {
          HttpContext.Current.Items.Add( SOMEKEY, value );
      }
   }
 }

and then

Foo.SingleRequestVariable = "bar"; // somewhere
...
string val = Foo.SingleRequestVariable; // yet somewhere else
like image 96
Wiktor Zychla Avatar answered Oct 05 '22 13:10

Wiktor Zychla