Singleton: Controlling Access to a Shared Instance
Design Patterns Explained: From Theory to Practice: Article 6
Creating objects is usually straightforward. The challenge sometimes lies in controlling how many instances of a particular object should exist.
Imagine a ticket-management application where multiple services need to record operational metrics, such as the number of tickets created at each priority level.
If every service creates its own metrics collector, each instance maintains a separate set of counters. One service might report 10 high-priority tickets while another reports 15, even though both are observing the same application.
We could solve this by passing the same collector instance to every service. However, we also need to ensure that another part of the application cannot accidentally create a separate instance.
This raises an interesting design question: what if a class should have only one instance, with a controlled way for different parts of the application to access it?
This is where the Singleton pattern becomes useful.
What is the Singleton pattern?
Singleton is a creational design pattern that ensures a class has only one instance and provides a global point of access to that instance.
Instead of allowing clients to instantiate the class directly, the class controls its own construction and returns the existing instance whenever another part of the application requests it.
In our ticket-management application, a single metrics collector can maintain shared in-memory counters for ticket creation across the application.
The central idea is that every client accesses the same object rather than creating independent instances.
However, there is an important distinction: Singleton controls the number of instances, but it does not automatically make the instance thread-safe or suitable for global use.
These considerations are particularly important in applications that handle multiple requests concurrently.
Understanding the structure
Unlike some of the other creational patterns, Singleton has a relatively simple structure.
It primarily involves two participants:
| Participant | Ticket-management example | Responsibility |
|---|---|---|
| Singleton | TicketMetricsCollector |
Controls its own instantiation and provides access to the shared instance |
| Client | TicketCreationService |
Accesses and uses the shared instance |
The Singleton class typically has three important characteristics:
- A private constructor: Prevents clients from creating instances using the
newkeyword. - A private static field: Stores the single instance of the class.
- A public static access point: Allows clients to retrieve the shared instance.
The instance can be created immediately when the class is initialised, or it can be created only when it is first requested. The latter approach is known as lazy initialisation.
The choice between these approaches depends on the application's requirements, particularly when object construction is expensive or the instance may never be needed.
Implementing Singleton in C#
Let's implement the pattern using our ticket-management application.
We will create a TicketMetricsCollector that records the number of tickets created at each priority level.
Step 1: Define the Singleton class
First, define the ticket priority enumeration and the Singleton class.
using System.Collections.Concurrent;
public enum TicketPriority
{
Low,
Normal,
High,
Critical
}
public sealed class TicketMetricsCollector
{
private static readonly Lazy<TicketMetricsCollector> _instance =
new(() => new TicketMetricsCollector());
private readonly ConcurrentDictionary<TicketPriority, long>
_createdByPriority = new();
private TicketMetricsCollector()
{
}
public static TicketMetricsCollector Instance => _instance.Value;
public void RecordTicketCreated(TicketPriority priority)
{
_createdByPriority.AddOrUpdate(
priority,
1,
(_, current) => current + 1);
}
public long GetCreatedCount(TicketPriority priority)
{
return _createdByPriority.TryGetValue(
priority,
out var count)
? count
: 0;
}
}
There are several important details in this implementation.
The constructor is private.
The application cannot create a new TicketMetricsCollector using new TicketMetricsCollector(). Construction is controlled by the class itself.
The class is sealed.
This prevents other classes from inheriting from it. It also avoids introducing additional instance-creation behaviour through subclasses.
The instance is stored in a static field.
The _instance field is shared by the class rather than belonging to an individual object.
The Lazy<T> class handles initialisation.
The Lazy<TicketMetricsCollector> instance delays construction of the actual collector until its Value property is accessed.
By default, the Lazy<T>(Func<T>) constructor uses a thread-safe initialisation mode called ExecutionAndPublication. If multiple threads attempt to initialise the value concurrently, the initialisation factory executes once and the resulting instance is published to the callers.
You can read more in Microsoft's Lazy initialisation documentation.
Step 2: Understand the importance of thread safety
A Singleton can be accessed by multiple parts of an application, potentially at the same time.
Consider what happens when two HTTP requests attempt to record a newly created ticket simultaneously.
Both requests need to update the same metrics collector. If the collector uses ordinary mutable collections without appropriate synchronisation, concurrent updates could cause incorrect results or race conditions.
This is why the implementation uses ConcurrentDictionary.
Its AddOrUpdate() method provides thread-safe updates to the counters, allowing multiple requests to record ticket creation without manually managing locks.
There are two separate thread-safety concerns here:
Lazy<T>protects the creation and publication of the Singleton instance.ConcurrentDictionaryprotects the shared collection against concurrent operations.
This distinction is important. Making Singleton initialisation thread-safe does not automatically make every operation on the resulting object thread-safe.
One additional detail is worth noting: the update delegate passed to AddOrUpdate() can execute more than once under contention. Our lambda simply calculates the next counter value, so it has no external side effects. In general, update delegates should not perform operations that must execute exactly once.
The class must still protect its own shared mutable state.
Step 3: Access the Singleton instance
Now that the class controls its own construction, clients can access the shared instance through the static Instance property.
For example, a ticket creation service can record metrics after successfully creating a ticket:
public sealed class TicketCreationService
{
public void RecordCreatedTicket(Ticket ticket)
{
TicketMetricsCollector.Instance.RecordTicketCreated(
ticket.Priority);
}
}
Another service can access the same collector:
public sealed class TicketReportingService
{
public long GetCreatedCount(TicketPriority priority)
{
return TicketMetricsCollector.Instance
.GetCreatedCount(priority);
}
}
Both services access the same TicketMetricsCollector instance.
The reporting service therefore sees the counters updated by the ticket creation service rather than maintaining a separate collection of metrics.
This demonstrates the central purpose of the pattern: controlling object creation while providing a shared point of access.
It is worth noting that these counters are held in memory. They are useful for demonstrating shared process-level state, but they are not a durable source of truth. Restarting the application resets them, and separate application instances maintain separate counters.
A production monitoring solution would normally use a dedicated metrics or telemetry system rather than relying on an in-memory Singleton as its reporting database.
When should you use Singleton?
Singleton is useful when a class genuinely needs one shared instance within a particular application context.
Common scenarios include:
- Application-wide configuration: Providing access to configuration data that is intended to be shared throughout an application.
- In-memory caching: Maintaining a shared cache that can be accessed by different services.
- Metrics and telemetry: Coordinating process-level counters or other shared measurements.
- Shared resource management: Managing access to a resource that is intentionally represented by one object within the application.
- Expensive initialisation: Avoiding repeated initialisation when a reusable object is genuinely expensive to create.
However, the requirement for a single instance should be genuine.
A class should not become a Singleton simply because developers want to avoid using the new keyword or believe that creating multiple objects is always inefficient.
Modern applications can create many lightweight objects without introducing meaningful performance problems.
The pattern is most useful when the application's design requires shared identity or coordinated state, not simply when an object is reused.
Advantages and disadvantages
Singleton has some useful characteristics, but it also introduces architectural trade-offs that should be considered before adopting it.
Advantages
- Controlled instantiation: The class prevents clients from creating additional instances through its public API.
- Shared access: Different parts of the application can work with the same object.
- Lazy initialisation: The instance can be created only when it is first required.
- Centralised state: Shared information can be maintained in one place within the application's context.
Disadvantages
- Global state: A globally accessible instance can introduce hidden dependencies and make it harder to understand how different components interact.
- Testing difficulties: Tests may interfere with each other when they share mutable Singleton state. Resetting or replacing the instance can also be difficult.
- Thread-safety requirements: Shared mutable state must be designed to support concurrent access.
- Reduced flexibility: Clients that depend directly on a static Singleton are tightly coupled to its concrete implementation.
- Lifecycle limitations: A traditional Singleton does not naturally support different instances for different users, requests or scopes.
Another concern is the Single Responsibility Principle. A Singleton class is responsible for its business behaviour as well as controlling its own instantiation.
This does not automatically make every Singleton a violation of SOLID, but it is worth considering whether the additional responsibility is justified.
The pattern can also hide architectural problems. When many unrelated services rely on globally accessible objects, it becomes difficult to identify dependencies and understand the application's overall structure.
Singleton in modern .NET applications
The traditional Singleton pattern is still useful to understand, but modern .NET applications already have a mechanism for managing object lifetimes through dependency injection.
ASP.NET Core provides three common service lifetimes:
- Transient: A new instance is created whenever the service is requested.
- Scoped: One instance is created per dependency injection scope, typically corresponding to an HTTP request.
- Singleton: The same instance is returned for subsequent requests from the same service provider.
For many application services that require shared lifetime, dependency injection can manage the Singleton lifetime without requiring a private constructor or a static Instance property.
Registering a Singleton service
In Program.cs, we can register a metrics collector using AddSingleton():
builder.Services.AddSingleton<
ITicketMetricsCollector,
TicketMetricsCollector>();
There is an important implementation difference here.
This DI-managed version is an alternative to the traditional Singleton class shown earlier. We would modify TicketMetricsCollector to implement ITicketMetricsCollector, expose a public constructor that the dependency injection container can use, and remove the private constructor, Lazy<T> field and static Instance property.
The container, rather than the class itself, now controls instance creation and lifetime.
The interface defines the operations that application services need:
public interface ITicketMetricsCollector
{
void RecordTicketCreated(TicketPriority priority);
long GetCreatedCount(TicketPriority priority);
}
The DI-managed implementation retains the same thread-safe counter behaviour:
public sealed class TicketMetricsCollector
: ITicketMetricsCollector
{
private readonly ConcurrentDictionary<TicketPriority, long>
_createdByPriority = new();
public TicketMetricsCollector()
{
}
public void RecordTicketCreated(TicketPriority priority)
{
_createdByPriority.AddOrUpdate(
priority,
1,
(_, current) => current + 1);
}
public long GetCreatedCount(TicketPriority priority)
{
return _createdByPriority.TryGetValue(
priority,
out var count)
? count
: 0;
}
}
The service can then receive the collector through constructor injection:
public sealed class TicketCreationService
{
private readonly ITicketMetricsCollector _metrics;
public TicketCreationService(
ITicketMetricsCollector metrics)
{
_metrics = metrics;
}
public void RecordCreatedTicket(Ticket ticket)
{
_metrics.RecordTicketCreated(ticket.Priority);
}
}
The service depends on an abstraction rather than directly accessing a static instance.
This makes it easier to replace the implementation, provide a test double and control the dependency during testing.
There is an important distinction here: a DI-managed Singleton is guaranteed to be shared within the relevant service provider. It is not necessarily one instance across every process or server running the application.
For example, if an application is deployed to three separate server instances, each instance has its own dependency injection container and its own Singleton instance.
This is not the same as a distributed Singleton shared across an entire infrastructure.
Important considerations with DI-managed Singletons
Although dependency injection manages the lifetime, it does not automatically make a Singleton service thread-safe.
Microsoft's guidance is clear: Singleton services must be designed for concurrent access, particularly when they maintain mutable state.
There is also a service lifetime consideration.
A Singleton should not directly capture a scoped dependency such as an Entity Framework Core DbContext. Doing so can cause a scoped dependency to be retained for the lifetime of the Singleton, creating unintended behaviour and lifetime problems.
In fact, DbContext should not normally be registered as a Singleton. It is designed around a short-lived unit of work, and it is not thread-safe. In typical ASP.NET Core applications, AddDbContext() registers it as scoped by default.
For more information, see Microsoft's documentation on dependency injection service lifetimes and DbContext lifetime and configuration.
The practical lesson is that Singleton lifetime should be selected deliberately. It is not a default choice for every service that multiple parts of an application need to use.
Singleton vs static classes
Singleton and static classes are sometimes confused because both provide access to shared functionality without requiring clients to create ordinary instances.
However, they are not interchangeable.
| Aspect | Singleton | Static class |
|---|---|---|
| Instance | One controlled object instance | No object instance |
| Construction | Controlled by the class | No instance construction |
| Interfaces | Can implement interfaces | Cannot implement instance interfaces |
| Inheritance | Can inherit from a base class | Cannot be instantiated or used as a base class |
| Dependency injection | Can be registered as a service | Cannot be registered as an ordinary instance service |
| State | Can hold instance state | Uses static state |
A Singleton is still an object. It can implement interfaces, participate in object-oriented relationships and be passed to other classes as a dependency.
A static class, on the other hand, is more restrictive. Its members belong to the type itself rather than to an object instance.
Use a static class for stateless utility functionality where object identity and dependency substitution are unnecessary. Consider a Singleton when the application genuinely needs one shared object with controlled lifetime and state.
Singleton vs the other creational patterns
We have now explored all five creational patterns in this series. Although they all deal with object creation, each addresses a different problem.
| Pattern | Main responsibility | Typical question |
|---|---|---|
| Factory Method | Delegates the choice of concrete product creation | Which implementation should be created? |
| Abstract Factory | Creates families of related products | Which compatible set of objects should be created? |
| Builder | Controls step-by-step construction | How should this complex object be assembled? |
| Prototype | Creates objects by copying existing instances | Can we start with an existing configuration and customise a copy? |
| Singleton | Controls the creation of a single shared instance | How do we ensure clients use the same instance? |
Factory Method focuses on selecting a concrete implementation.
Abstract Factory focuses on creating compatible families of objects.
Builder focuses on controlling the steps required to construct a complex object.
Prototype focuses on creating new objects by copying existing instances.
Singleton focuses on ensuring that only one instance is available through a controlled access point.
These patterns are not competing solutions. They address different object-creation requirements and can sometimes be combined.
Conclusion
Singleton provides a controlled way to ensure that a class has only one instance and that different parts of an application can access that same object.
In our ticket-management application, the metrics collector demonstrates how a shared instance can maintain process-level state across multiple services.
However, the pattern introduces global access, shared-state and testing concerns that should not be ignored. Thread safety must also be considered whenever multiple requests can access the same instance concurrently.
Modern .NET applications can often achieve the required lifetime through dependency injection without implementing a traditional static Singleton. This generally provides better flexibility and makes dependencies easier to test.
The real skill is recognising when a single shared instance is an actual requirement and when dependency injection with a different service lifetime is the simpler design.
With Singleton, we have completed the five creational design patterns.
Next, we move into the structural design patterns, which focus on how classes and objects are organised and combined to form larger, more maintainable structures.
The first pattern in this category is Adapter, which explores how we can make incompatible interfaces work together without changing their existing implementations.
Further reading
- Singleton — Refactoring.Guru
- Dive Into Design Patterns — Alexander Shvets, Singleton chapter.
- Design Patterns in C#, 2nd Edition — Vaskaran Sarcar, Singleton chapter.
- Microsoft Learn — Dependency injection service lifetimes
- Microsoft Learn — Dependency injection guidelines
- Microsoft Learn — Lazy initialisation
- Microsoft Learn — DbContext lifetime and configuration
Comments
Join the discussionNo comments yet. Be the first to comment.