The three methods control how long an object lives:
Transient: a new instance every time it is requested. Good for small, stateless helpers.
Scoped: one instance per scope, which in a web app means per HTTP request. The usual choice for services that use a database context.
Singleton: one instance for the whole life of the app. Use it for caches, configuration and expensive objects. It must be thread-safe, because many requests share it.
Rules that prevent bugs:
A singleton must not depend on a scoped service. The scoped object would be kept alive far longer than intended.
Never keep per-user data in a singleton field.
DbContext should be scoped, not singleton.
So AddScoped is a sensible default for request work, but caches and clients such as HttpClient factories fit singleton or transient better.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
The three methods control how long an object lives:
Rules that prevent bugs:
So AddScoped is a sensible default for request work, but caches and clients such as HttpClient factories fit singleton or transient better.