This is a duplicate of: What is a singleton in C#?
How to implement a Singleton so that object instance can be released/disposed when all it's references are not in use? And when ever any body wants a Singleton instance it is lazy loaded on demand.
Singletons are not supposed to be disposed of dynamically: once created, they exist till the end of the application's lifetime. Singleton means there is one and only one instance of it.
Even if your Singleton reserves a resource which you want to dynamically release and re-reserve, you shouldn't destroy and rec-create the Singleton instance. That would contradict with the common meaning and usage of the pattern, which can (at best) cause communication problems in your team, or (at worst) subtle bugs in your app.
Instead, you could have the Singleton object internally manage that resource: release it if it hasn't been used for some time, or if its reference count drops to 0.
You should also consider using a Factory instead to access that resource. This gives you much more freedom to control the handling of the resource in question. You can also reuse the created object internally, in effect keeping object count to at most 1.
As some other answers say, Implementing the Singleton Pattern in C# is one of the best resources for Singletons in general.
If you want your singleton to be released when it's not referenced anywhere else, you might take your favorite pattern off the aforementioned site and wrap the instance into a WeakReference, for example something like:
public sealed class Singleton
{
static private readonly WeakReference _instanceReference =
new WeakReference(Singleton.LoadInstance());
static public Singleton Instance
{
get { return Singleton.GetInstance(); }
}
static private Singleton() { }
static private Singleton LoadInstance()
{
// load from expensive resource;
return new Singleton();
}
static private Singleton GetInstance()
{
Singleton result = _instanceReference.Target as Singleton;
if (result == null)
{
// TODO: consider thread safety
result = LoadInstance();
_instanceReference.Target = result;
}
return result;
}
private Singleton()
{
//
}
}
Be aware that consumers most likely would merely call your Singleton.Instance
and won't create a reference by themselves, which means your resource would get reloaded quite often. I guess this pattern works best if the Singleton Instance would sometimes be a member of certain classes you pass around.
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