Q1. What are the three DI lifetimes?

.NET DI has three primary lifetimes:

  • Transient → new instance every time requested
  • Scoped → one instance per scope, typically one HTTP request
  • Singleton → one instance for the lifetime of the DI container/application

Memory trick:
T = Tiny/stateless → S = Scope/request → S = Shared/application

How do you decide which DI lifetime to use?

Best Interview Answer

“I don’t choose a DI lifetime based purely on convention. I look at the service’s state, ownership, construction cost, concurrency requirements, and dependency graph.

Stateless lightweight services are generally transient. Request-specific services and unit-of-work components such as EF Core’s DbContext are scoped. Application-wide immutable or thread-safe state can be singleton.

I also make sure I don’t inject scoped dependencies into singletons because that creates a lifetime mismatch. And in a distributed environment such as ECS, I remember that a .NET singleton is process-local, so shared state belongs in something like Redis rather than an in-memory singleton.”

Lifecycle and where to use

Transient

Keywords: Stateless, Lightweight, Cheap

Use it for lightweight services that don’t need shared state.

Singleton

Keywords: Shared, Immutable, Thread-safe, Application-wide

Use it when the object can safely be shared across requests and doesn’t contain request-specific state.

LifetimeInstance creationTypical lifetimeTypical use
TransientEvery resolutionVery shortStateless/lightweight services
ScopedOnce per scopeUsually HTTP requestDbContext, business services
SingletonOnceApplication/container lifetimeShared thread-safe state, caches

Real World Decision Matrix

Q2. Why is DbContext Scoped?

Keywords: Unit of Work, Change Tracking, Not Thread Safe, Request

DbContext maintains state and change tracking and is designed around a unit-of-work pattern. Sharing it across concurrent requests is unsafe.

Q3. What happens if Singleton depends on Scoped?

Keywords: Lifetime mismatch, Captured dependency, Request state

A longer-lived service can capture a shorter-lived dependency. This is generally invalid and can cause incorrect lifetime behavior.

Q4. Can Scoped depend on Singleton?

Answer: Yes, provided the Singleton is safe for concurrent access and does not depend on scoped/request-specific state.

Q5. Is Singleton shared across ECS tasks?

Answer: No. A .NET Singleton is process/container-local. Three ECS tasks mean three Singleton instances.

Q6. Is Singleton shared across Lambda invocations?

Answer: It may survive across invocations within a reused Lambda execution environment, but it is not globally shared across Lambda environments.