The Singleton Design Pattern in C# ASP.NET

 
Written by Mark Pringle |
Published on:

Singleton is a creational design pattern that ensures that only one class instance will be created while providing a global access point to this instance. This pattern ensures application-wide common functionality because only a single class instance can exist.

Use this pattern when it does not make sense to instantiate a new object or when resources are too expensive to instantiate.

Since design patterns are reusable solutions to problems, it is crucial to address the problem and solution for the Singleton design pattern.

Problem

  • Objects instantiated using the new keyword in ASP.NET C# give all new objects concurrent access to the same shared resource.
  • Creating multiple new objects for a class is hard to maintain.

Solution

  • One instance of a class and one global access point.
  • Only one object is using resources because only a single object exists.

The Difference Between a Static Class and a Singleton

The preceding raises another question. What is the difference between a static class and a Singleton since both can be invoked without instantiation and can be created to provide a central point of access, meaning there's only one instance and one way to access it?

Singletons are objects. 

  • Singletons can pass around the object for delegates and callbacks
  • Singletons allow you to implement interfaces.
  • With Singletons, you can use a Factory Pattern to build up your instance.
  • Singletons can be extended.
  • Singletons can be passed as objects.
  • Singletons can be inherited.
  • The scope of Singleton is at the application level.

A static class is a container for sets of methods that operate on input parameters. 

  • Static classes cannot inherit their instance members.
  • Static classes are sealed and, therefore, cannot be inherited.
  • Static classes are rigid.

Sample Singleton Code

Visual Studio Singleton in Console App

There are various ways of implementing the Singleton pattern in C#. We will create a lazy-loaded, thread-safe example using Visual Studio's Console App template in this example. The Console App template code below uses .NET 6. Remember that the project template generated for new .NET 6 console apps has recent C# features that simplify the code you need to write for a program. So, the Program.cs file may look different if you are using .NET 5 or below.

To create a lazy-loaded, thread-safe Singleton, do the following:

  1. Create a new public and sealed class.
  2. Declare a constructor that should be private and parameterless.
  3. Seal the class to ensure that it cannot be inherited.
  4. Create a private static variable to hold a reference to the single created instance.
  5. Create a public static property that will return the single instance of the Singleton class
LearnSingleton.LetsPlay();

public sealed class LearnSingleton
{
    //Create a private static variable to hold a reference to the single created instance
    //Initialized with null for lazy instantiation
    //Ensures that only one instance of the object is created
    private static LearnSingleton? instance = null;

    //Locking ensures that all reads occur logically after the lock is acquired
    private static readonly object padlock = new object();
    private LearnSingleton()
    {
    }

    //Create a public static property which will return only a single instance of the singleton class
    //Expose the class as public so that it can be used by other code.
    public static LearnSingleton Instance
    {
        get
        {
            //Locking ensures that all reads occur logically after the lock is acquired
            lock (padlock)
            {
                //Assign a new instance of the singleton class
                //Use compound assignment and null-coalescing operators
                instance ??= new LearnSingleton();
                return instance;
            }
        }
    }

    //Add a sample test method to see that this code has been called
    public static void LetsPlay()
    {
        Console.WriteLine("LearnASPNET.com is Cool. Singleton.");
    }
}

When the console is started without debugging...

Singleton Console Example

Copyright © TravelDailyLife.com

Author: Mark Pringle
I'm just a guy who is addicted to the unfamiliar and who fulfills this addiction by traveling and writing about my travels. As a lover of sports, penning opinion articles related to sports is also a pastime.
My External Website (External Website Opens in New Window)

Comments

Please Login to Comment
No comments have been posted. Be the first.



Hire a Writer