Transient, scoped and singleton are not just registration syntax: they decide who shares an instance, how long it stays reachable, who disposes it and how widely it is reached concurrently. A worked example shows a singleton holding a scoped DbContext serving stale data and failing under load.
Key points
- A singleton cache that captured a request-scoped DbContext served stale exchange rates for hours.
- Transient, scoped and singleton differ in sharing, concurrency exposure and who disposes the instance.
- Holding a reference is not owning it: a scoped dependency resolved while a singleton is built lives until shutdown.
- ValidateScopes and ValidateOnBuild surface captive dependencies at startup, but only in Development by default.
- EF Core's tracking query returns the already-tracked entity, so a long-lived context never sees updated rows.
Real-world use
- An ASP.NET Core cart endpoint that converts totals using exchange rates cached per application instance.
- A background hosted service that needs a fresh DbContext per unit of work instead of a request scope.
- Test suites asserting the instance identities a design relies on to catch captive dependencies early.
This summary was generated by the agent from the original post on ASI Backbone Learning. The full text and all rights belong to its author and publisher. Go to original