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

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

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.

Reusable, named solutions to recurring design problems. GoF (1994) lists 23 in three categories: Creational (Singleton, Factory Method, Abstract Factory, Builder, Prototype), Structural (Adapter, Bridge, Composite, Decorator, Facade, Flyweight, Proxy), Behavioural (Chain of Responsibility, Command, Interpreter, Iterator, Mediator, Memento, Observer, State, Strategy, Template Method, Visitor).

Use Lazy<T>: private static readonly Lazy<Svc> _i = new(() => new Svc()); public static Svc Instance => _i.Value; with a private constructor and a sealed class. Lazy<T> is thread-safe by default (ExecutionAndPublication). Alternatives: a static readonly field (thread-safe because of the type initialiser), or double-checked locking with volatile. In ASP.NET Core, prefer services.AddSingleton<ISvc, Svc>(). It's testable and the container manages the lifetime.

Source: DEV - interview — Read the full article on the original site ↗

By Admin