Singleton Patterns in C# or MVC Core?

Singleton Design Pattern :- As the name suggests singleton has only one instance to be created for a class and it is globally access all over the application or we can say that a singleton is a class that allows only single instace of itself to be created. This is most popular and widely used design pattern for accessing centralized resource with creating a single object of class.This pattern belongs to Creational Design Patterns.
This pattern is used when we need to ensure that only one object of a particular class needs to be created and all further references to the Objects are referred to the same underlying instance created.
Singleton is used for accessing a resource with centralized access for example if you want to implement logging functinality in your application then we can do it with Singleton class where one global instance of the logger class needs to be created and it is used for log all the information throughout the application.

Below are some Implementation Guidlines for Singleton Class that we need to follow.

  • Declare a Constructor that should be Private and Parameterless so that this private constructor will create only one single instance and will restrict the class being instantiated from outside the class.It only instantiates within the Class.
  • Declare the Class as Sealed so that it will guarntee that no any other sub class will inherit this Class in case of Nested Classes.
  • Create a Private Static variable that will reference the Singleton Class Instance.
  • For checking whether an instance of singleton class is created or not then we must create a Public Static Method/Property that will return the singleton instance of the Method/Property if it is true otherwise it will create a instance for it.

Examples of Singleton Design Pattern in C#

                
 public sealed class SingletonExample
    {
        private static int counter = 0;
        private static SingletonExample instanceSingleton =null;

        public static SingletonExample GetInstanceSingleton
        {
            get
            {
                if(instanceSingleton == null)
                {
                    instanceSingleton = new SingletonExample();

                }
                return instanceSingleton;
            }
        }
        private SingletonExample()
        {
            counter++;
            Console.WriteLine("Counter values for counting the constructor instances :-  " + counter);
        }
        public void PrintLogInfo(string Message)
        {
            Console.WriteLine("Logging information displayed:- " + Message);
        }
    }
                 
                

Step by Step Explanation of above code written for Singleton Pattern:-

  • In the above Singleton example we created a class SingletonExample and make it Sealed because no any other classes/subclasses will inherit this class ,Sealed will restrict them to inherit. We have used a Static variable counter of Integer type for counting the Instanced created by the class, initially we initialized it with 0 and increment it in Private Constructor when a new instance is created to check whether Singleton Class created exact one Instance or more than one instances.
  • We declared a Private Static instance of SingletonExample class and initialized it with null.
  • Then declared a Static property GetInstanceSingleton and inside the property will check if instanceSingleton is null then only we will create a new instance of SingletonExample class and will return the instanceSingleton.
  • Now create a Private Parameterless Constructor of SingletonExample class so that it will ensure that only single instance will create for this class throughout the application and incremet the counter variable here and print the counter value only for our confirmation to check whether Singleton is working fine or not.
  • Write a Public Method PrintLogInfo having one input parameter Message of string type and it will display a logging information on console when calling this method from Program class by Singleton instance.

                
 internal class Program
    {
        static void Main(string[] args)
        {

            SingletonExample singleton = SingletonExample.GetInstanceSingleton;
            singleton.PrintLogInfo("Invalid username/password");
            SingletonExample singleton1 = SingletonExample.GetInstanceSingleton;
            singleton1.PrintLogInfo("Network connectivity lost");

            Console.ReadKey();
        }
    } 
                 
                

Below is the Output of Singleton Design pattern implementation program.

Image is not available

In the above code we have created a instance of SingletonExample class using the GetInstanceSingleton property and with this instance called PrintLogInfo method with "Invalid username/password" as a string message.Now create a second instance of this class and called the same method again you can see the output of the program in above image that counter still having 1 as output and two message has been displayed on the console, so we have concluded it is working as expected.

Image is not available

About the Author
Sudheer Singh Chouhan is a Software Engineer having Expertise in Development Design and Architecting the applications , Project Management , Designing Large Scale Databases in SQL Server since last 17 Years.
Skill Sets :- Microsoft .NET technologies like ASP.Net Core, Web API, LINQ, Web Forms, WinForms, SQL Server, EntityFramework, Design Patterns, Solid Principles, Microservices, AWS Cloud.