Tutorials Design Patterns in C#
Singleton Pattern — Complete Guide
Singleton Pattern — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of Design Patterns in C# on Toolliyo Academy.
On this page
Design Patterns in C# · Lesson 1 of 69
Singleton Pattern
GoF Core → Enterprise → Cloud & Craft
GoF Core · 1 — Create & structure · ~6 min · Module 1: Creational Design Patterns
What is this?
Singleton ensures a type has one shared instance and a global access point. In modern .NET you often prefer DI lifetimes instead of a classic static singleton.
Why should you care?
ShopNest may want one in-process cache coordinator — but a careless singleton becomes a hidden global that ruins tests.
See it live — copy this example
Paste into a C# console or class library project and run dotnet run.
public sealed class ShopNestConfig
{
private static readonly Lazy<ShopNestConfig> _lazy =
new(() => new ShopNestConfig());
public static ShopNestConfig Instance => _lazy.Value;
public string ConnectionName { get; init; } = "ShopNest";
private ShopNestConfig() { }
}
Console.WriteLine(ShopNestConfig.Instance.ConnectionName);
Run Example »
Edit the code below and click Run to see the result in Toolliyo’s live editor.
What happened?
- Lazy
creates the instance once in a thread-safe way. - The private constructor blocks new ShopNestConfig().
- Prefer services.AddSingleton
() in ASP.NET Core for testability.
Practice next
- Create a console app and paste the example.
- Print Instance twice and confirm the same values.
- Try new ShopNestConfig() and see it fails to compile.
- Add a second property and read it from Instance.
- Replace with DI AddSingleton and resolve twice.
Remember
One instance, controlled access. Lazy
ShopNest process-wide feature flags
A small in-memory flag reader registered as singleton.
Outcome: All requests see the same flag snapshot without a static mess.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!