Duplicate
On design patterns: When should I use the singleton?
class Singleton
{
private static Singleton instance;
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
instance = new Singleton();
return instance;
}
}
}
You should use a Singleton when there should only be one instance of an object. However, Misko Hevery has some thoughts on why Singletons are bad!
You could find the singleton pattern useful if you have a resource that costs a lot to get initialized, and that you use several times, such as an object context when you use an ORM or a connection of some sort.
Obviously you must pay attention that keeping that thing alive does not cost you more than recreating it every time.
Note that this code is not thread safe:
One thread could enter the function, get past the test for null and then be suspended. A second thread could then start and get past the null test. From that point on, both threads will at some point create their own copy of the sungleton object, only one of which gets used.
This may not matter so much in a GC language like C#, but if the singleton controls rresources other than memory, then it does matter. You need to use the double-checked locking pattern to prevent it.
Assuming your question is in the title:
I once worked with a COM object that could only have one instance per server. We exposed it to the entire ASP.NET application through a singleton.
Jon Skeet, THE_SKEET, has a great article exemplifying various ways to implement correctly (Thread safe, lazy, performant) the Singleton pattern.
Go read it here.
By popular demand (er... downvote) I reproduce the Skeet version:
In my project we created a logger component which is getting used for logging in the application to different sources (e.g. text file, XML, and database, based on configurations). So there is a log manager which creates the only one instance of the logger class across the application for logging the message, errors, etc.