using
Systemnamespace DesignPattern
{
class Connection
{
private static Connection instance;
private Connection()
{
}
public static Connection GetInstance()
{
if(instance == null)
{
instance = new Connection();
return instance;
}
else
return instance;}
}
}
Now this is a singleton class .So every consumer of this class will get an single instance of this class.
My question is that when and how the instance of this singleton object will be disposed..
An extended example would be great.

When and how the instance of a singleton object will be disposed..?
Greg Dirst
If you desire your instance to be created on demand and destroyed when no longer in use (and recreated if requested again), you might use reference counting. Something like the following crude example:
class Connection {
private static Connection instance = null;
private static int users = 0;
private Connection () { ... }
public static Connection GetInstance () {
if (instance == null) {
users = 1;
return (instance = new Connection ());
} else {
users++;
return instance;
}
}
public static void ReleaseInstance () {
users--;
if (users == 0) {
instance = null; // devise your own releasing mechanism
}
}
}
class ConnectionWrapper : IDisposable {
private Connection instance;
public ConnectionWrapper () {
instance = Connection.GetInstance ();
}
public void Dispose () {
Connection.ReleaseInstance ();
instance = null;
}
}
I omitted locking, destructors and the like... to use the instance, either provide wrapper methods in ConnectionWrapper or expose instance through a property. You might also consider making Connection a nested private class of ConnectionWrapper, to enforce the correct use.
Just my 2 cents
--mc
XanthViper
I agree with you.....
But when should I call the Dispose
dkbryan
You can dispose the object when you do not need it anymore, end of a operation or application end.
If you do not use unmanaged resources in your singleton you do not need to explicitly dispose it.
Niklas_
However, if you do use unmanaged resources in your singleton, this is a good place to implement a Finalizer (i.e. c#'s 'destructor'). This way, when the application would end, collection of the object would be made and the finalizer will be called to free everything.
Also, make sure you know what you're following all best practices about writing a finalizer, such as making sure things haven't been collected already, etc.
You might want to consider a manual call to a method that would do the same things the finalizer would do, since the time the finalizer starts is undetermined and some objects may already be collected by the time the finalizer runs.
It is rarely the case that a singleton would implement IDisposable, since the interface will almost never be consumed (unless you want a big 'using' statement around your whole app :P).
Hope this helps.
pdhot
What do you mean by disposed
The class doesn't implement IDisposable. And if it did, you would have to call IDisposable.Dispose explicitly in your code somewhere.