Design Patterns Made Simple Singleton Design Pattern in .NET
Sometimes, an application needs only one instance of a particular class. Creating multiple instances may be unnecessary or may lead to inconsistent application behavior.
This is where the Singleton design pattern becomes useful.
Think of an office with a single reception desk. Employees and visitors approach the same reception desk instead of creating a new one every time they need assistance.
The Singleton pattern follows a similar concept. It restricts the creation of a class to one instance and provides a common way to access it.
A Simple C# Example
public sealed class AppSettings
{
private static readonly AppSettings _instance = new();
private AppSettings() { }
public static AppSettings Instance => _instance;
public string ApplicationName => "My Application";
}We can access the same instance from different parts of the application:
var settings = AppSettings.Instance;
Console.WriteLine(settings.ApplicationName);In this example, the private constructor prevents external instantiation, while static initialization provides thread-safe instance creation.
Where Can We Use It?
Common scenarios include shared configuration, caching services and application-wide services.
In modern ASP.NET Core applications, we can also manage singleton lifetimes through dependency injection using AddSingleton<T>(), which provides a shared instance per service provider.
Architect's Takeaway
Singleton is useful, but it should not become an excuse for introducing global state.
Consider thread safety, testability and dependency lifetimes before adopting it. Also remember that a singleton does not automatically provide one shared instance across multiple servers.
Use it when a single shared instance is genuinely required, not simply because it is convenient.
