C# Singleton Design Pattern
The Singleton Design Pattern belongs to the creational category of design patterns. It restricts the instantiation of a class to one single instance and ensures that the same instance is reused across the application

Introduction
The Singleton Design Pattern belongs to the creational category of design patterns. It restricts the instantiation of a class to one single instance and ensures that the same instance is reused across the application.
🧪 Implementation Example in C#
Here’s a complete and testable example of implementing a Singleton in C#, adapted from a real-world pattern demo:
public class SingletonDatabase : IDatabase
{
private readonly Dictionary<string, int> capitals;
private SingletonDatabase()
{
capitals = File.ReadAllLines("capitals.txt")
.Batch(2)
.ToDictionary(
list => list.ElementAt(0).Trim(),
list => int.Parse(list.ElementAt(1))
);
}
private static readonly Lazy<SingletonDatabase> instance =
new Lazy<SingletonDatabase>(() => new SingletonDatabase());
public static IDatabase Instance => instance.Value;
public int GetPopulation(string name) => capitals[name];
}
🧪 Unit Testing the Singleton
[Test]
public void IsSingletonTest()
{
var db1 = SingletonDatabase.Instance;
var db2 = SingletonDatabase.Instance;
Assert.That(db1, Is.SameAs(db2));
}
This confirms that only one instance is created.
🔍 When Not to Use Singleton
While Singleton offers many advantages, it’s not suitable for every use case. Avoid Singleton when:
- You need different configurations in different parts of the app
- You're doing unit testing and want better decoupling
- You're working in a distributed system with multiple app instances
For testability, use dependency injection along with interfaces to swap implementations easily, as shown in the ConfigurableRecordFinder
.
🧰 Best Practices
- Use
Lazy<T>
for thread-safe instantiation. - Always use an interface (
IDatabase
) to make your Singleton swappable in testing scenarios. - Avoid using Singletons for stateful or session-based data.
🏁 Final Thoughts
The Singleton Design Pattern in C# is a powerful and practical pattern that helps developers manage resources and maintain a clean architecture. When implemented correctly — especially with attention to testability and thread safety — it becomes a rock-solid foundation in many .NET applications.
By understanding when and how to use it, you can build applications that are both performant and maintainable.