How to implement a Singleton pattern in C#

Singleton design pattern is one of the creational design pattern, originally designed by Gang of Fours.
Sometimes we want to have only a single point access to the functionality of the class. Our code expects that every time an instance of the class gets created it should return only a single instance of the class. In such situations this pattern come in handy.

There are many ways to create a class which returns a single instance. I am going to show one of it.

Implementation

I will create a private constructor of the class and will create a static property to get the access of the single instance of our class. Singleton object gets created lazily. i.e. an instance of the class gets created when a request to get the instance has been initialized first time.

I am going to show example from my one of the post which I wrote. In this post I had shown you how to host a WCF service in a window service.

In that post, WCF service is exposed to outside world, which can be accessed by many clients and messages received from all the requests are to be dispatched to SelfHostService class. So this makes a perfect scenario to expose our SelfHostService class as a singleton.

Lets have a look at a code which makes our class as singleton.

public class SelfHostService : ServiceBase
{
    private static SelfHostService instance = null;
    private static readonly object padlock = new object();
 
    //a private constructor
    SelfHostService()
    {       
    }
 
    //public static property to access the instance of the SelfHostService class
    public static SelfHostService Instance
    {
        get
        {
            lock (padlock)
            {
                if (instance == null)
                    instance = new SelfHostService();
 
                return instance;
            }
        }
    }
}

In above code a static property named Instance of type SelfHostService is created. This Instance property makes sure that only one instance is returned.

I have used lock statement to ensure that our code remains thread safe.i.e it assures that only one instance will get created of SelfHostService class.

This is one of the many ways to implement a singleton pattern in C#. To conclude, I can say that it would be more appropriate to make a singleton class as a Sealed class.

Enjoy Coding!!!!!

Do not forget to share this post if you like it.

About sagar

With over 13 years of professional experience as a .NET developer, I have honed my expertise in various facets of the .NET framework and related technologies. My extensive background includes proficiency in WPF, Web APIs, WCF services, and Windows services, which has enabled me to deliver robust and scalable applications across different domains.

Leave a Reply

Your email address will not be published. Required fields are marked *