Menu

Singleton — Design Patterns (GoF + Enterprise) in C#
📰

Singleton — Design Patterns (GoF + Enterprise) in C#

DEV Community: dotnet·DIVAKAR UPADHYAY·4 days ago
#LVK7yhuA
#devtodotnet#devto#dev#factory#method
Reading 0:00
15s threshold

Lesson 1 of 18 in the free Design Patterns (GoF + Enterprise) in C# course on DevLadder.

Ensure a class has one instance with a global access point.

// 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 >();

Enter fullscreen mode

Exit fullscreen mode

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 .

Interview questions on Design Patterns (GoF + Enterprise) in C

What are design patterns?…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.