Roadmap › Design Patterns (GoF + Enterprise) in C# › Module: Creational Patterns
Lessons in this course (18)
1. Singleton
Basic★ Must knowLesson 1 of 18
Ensure a class has one instance with a global access point.
csharp
// Thread-safe, lazy Singleton
public sealed class AppConfig
{
private static readonly Lazy<AppConfig> _instance = new(() => new AppConfig());
public static AppConfig Instance => _instance.Value;
private AppConfig() { /* load settings once */ }
public string ConnectionString { get; private set; } = "";
}
// Modern .NET: let the DI container own the lifetime instead
builder.Services.AddSingleton<IAppConfig, AppConfig>();Other thread-safe options: a static readonly field (initialised by the CLR's type initialiser, thread-safe), or double-checked locking. Downsides of the hand-written pattern: global state, hidden dependencies, hard to test. Prefer AddSingleton.