C# Interview Question #156

What is the Singleton Pattern, and how is it different from a DI singleton?

Design Patterns & Production Architecture Senior Advanced

Quick Interview Answer

The traditional Singleton Pattern ensures that a class controls creation of a single instance and exposes global access to it.

Detailed Explanation

The traditional Singleton Pattern ensures that a class controls creation of a single instance and exposes global access to it.

A DI singleton is different: the dependency-injection container manages one instance for the service-provider lifetime and injects it where required. This is usually preferable because dependencies remain explicit and testable.

Singleton services must be thread-safe when they contain mutable state and should not directly capture scoped services such as EF Core DbContext.

Code Example

builder.Services.AddSingleton<ICacheService, CacheService>();