ASP.NET Core Interview Question #58

When should you use a Singleton service?

Dependency Injection & Services Junior Beginner

Quick Interview Answer

A Singleton service is created once and reused for the lifetime of the application process. It is appropriate for services that are expensive to construct, hold application-wide immutable state, or safely manage shared state.

Detailed Explanation

A Singleton service is created once and reused for the lifetime of the application process. It is appropriate for services that are expensive to construct, hold application-wide immutable state, or safely manage shared state.

Because many requests can use a singleton concurrently, its implementation must be thread-safe. A singleton should not store per-user or per-request data in instance fields.

It must also avoid directly depending on scoped services. If scoped work is required, create a scope for that operation using IServiceScopeFactory.

Code Example

builder.Services.AddSingleton<ISystemClock, SystemClock>();

public class SystemClock : ISystemClock
{
    public DateTime UtcNow => DateTime.UtcNow;
}