wasAsked.

Explain DI lifetimes.

Altimetrik · Role not specified · technical

Published

Asked in 2026 · .NET

Community answers

Posted by wasAsked editorial collection

Lifetimes describe how long the dependency injection container reuses an object. Transient - Created every time it is requested, even several times within one request. - Suits small stateless services: mappers, validators, formatters. Scoped - Created once per scope. ASP.NET Core creates a scope for each HTTP request, so every class in that request receives the same instance. - Suits request-level state and units of work: EF Core DbContext, a "current tenant" or "current user" service. Singleton - Created once (on first use, or when you register an existing instance) and shared by every request and thread until the application stops. - Suits expensive or shared, thread-safe objects: configuration, memory caches, connection multiplexers such as Redis ConnectionMultiplexer. Quick demonstration: if you inject a service with each lifetime into two different classes and log a GUID created in its constructor, you will see transient GUIDs differ everywhere, scoped GUIDs match within a request but differ between requests, and the singleton GUID never changes. Rules that prevent bugs: - Do not inject a shorter-lived service into a longer-lived one (scoped into singleton). The container's scope validation catches this in Development. - Singletons must be thread-safe; use concurrent collections or immutable data. - Never store user-specific data in a singleton. - Disposable services are disposed by the container at the end of their scope (or at shutdown for singletons) — do not dispose injected services yourself. - Background services do not have a request scope; create one with IServiceScopeFactory when you need scoped services there.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics