Asp.net global variable depending on page life cycle?

Of course, this should be a common problem, but I cannot find an easy way to do this.

Is there a way to pass a global variable (say, a class that is expensive to instantiate) during the life cycle of an asp.net web form, without having to pass a handle to each individual page component?

If I just create a static variable, it will be accessible to all threads in the application domain (problem: my class is not thread safe) and it will be difficult to guarantee that every page will work with the last copy (I want to cache the class through every step of the page life cycle, but every time a new page is called, I want a new instance).

An alternative is to pass a descriptor through each control on the page, but between the main page, the page itself and all user controls, this makes the code pretty hairy.

I was wondering if there was an elegant solution for storing the class in some place, accessible only to the thread executing this particular page (including all sub-user elements)?

Any suggestion is welcome! thanks Charles

+5
source share
1 answer

There is a simple answer: the Items container. It is available for the life 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
+7
source

All Articles