ASP.NET Core dependency injection: choosing Singleton, Scoped and Transient
How dependency injection lifetimes affect requests, DbContext use and testability in ASP.NET Core.
Sample period date: Jun 5, 2020. These essays revisit earlier technologies from today's editorial perspective; they are not represented as posts originally published in those years.
Service lifetime is an architectural decision
A Singleton is shared for the application's lifetime, a Scoped instance usually belongs to one HTTP request and a Transient is created on each resolution. Choosing Singleton merely to reduce allocations is risky. Mutable state and concurrent requests can introduce bugs that only appear under production traffic.
DbContext is usually scoped
Entity Framework DbContext tracks entities and a unit of work. Sharing one context across the application can mix tracked entities and concurrent operations. A scoped context per request is the common safe default. Background jobs do not automatically have an HTTP request scope, so they must create and dispose an explicit scope when required.
Avoid captive dependencies
Injecting a Scoped service into a Singleton may trap request-specific state inside a long-lived object. That can leak data across requests or lead to unexpected sharing. Use container scope validation during development. Where appropriate, create an explicit scope through a factory or extract an interface that no longer depends on request state.
Verification plan
Send concurrent requests with different test data and trace service instance identities alongside request IDs. Repeat with a background worker. Verify timely disposal and that one request's data never appears in another. These checks prove more than a successful build.
Comments
0 real commentsNo real reader comments yet.
✎ Write a comment