> Hello
I'm writing an application in ASP.NET 1.1 and have come across a
problem using static fields in my page classes.
I have lots of controls on the page that all need to bind to the same
datasource, so I thought I'd create a singleton in the base class that
reads from the database and provides a DatasSet to all instances of the
various derived classes. I've discovered, though, that the static
values persist between roundtrips, presumably because the singleton
instance hasn't been released by the garbage collector. For this
reason, I've decided that using static in my ASP.NET pages is probably
unsuitable.
Does anyone have any recommendations for using static members in
ASP.NET, or is there a more appropriate method for implementing
singletons in ASP.NET?
Thanks a lot, Mark
A singleton should not be "released by the garbage collector". It
should remain alive for the duretion of the application.
An asp.net application is a single application that keeps on running
until you explicitly stop it. During this lifetime it serves many
sessions consisting of many requests.
It is possible to use static members and singletons in asp.net, but you
need to know the effects: *all* users will the use the *same*
instances. If that is what you want, fine.
What you may want is static *methods*. You don't need to instantiate
the class, you can (or rather: need to) call these on the *type*.
Example:
public sealed class MyLibrary
{
private MyLibrary() { } // no public constructor needed
public static DataSet GetData(int id)
{
// ....
return ..;
}
}
and you call that with:
DataSet ds = MyLibrary.GetData(1);
Hans Kesting