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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With