โ† Back to list

๐ŸŽ‰ DI Lifetimes in .NET Explained Like a Party You Actually Want to Attend

If youโ€™ve ever worked with .NET Dependency Injection, youโ€™ve met these three characters:

Redwan Niloy ยท 2026-02-15 19:55 ยท 3 claps ยท 1.4 min read
#dot-net-core #dependency-injection #singleton #transient #scoped
Open on Medium โ†—

๐ŸŽ‰ DI Lifetimes in .NET Explained Like a Party You Actually Want to Attend

If youโ€™ve ever worked with .NET Dependency Injection, youโ€™ve met these three characters:

Singleton, Scoped, and Transient.

At first, they sound harmless. Friendly, even.

And then one day your app throws a mysterious ObjectDisposedException, your logs start screaming, and you realizeโ€ฆ

You invited the wrong lifetime to the party.

Letโ€™s fix that. No boring textbook explanations. Just vibes, analogies, and fewer production bugs.

๐ŸŽญ Meet the Three Guests

๐Ÿ  Singleton โ€” โ€œI live here nowโ€

Only one instance for the whole application.

Created once.

Lives until the app shuts down.

Everyone shares it. Forever.

Think: the person who shows up early, takes the couch, and never leaves.

Good examples: Logger, Cache service, Configuration, HttpClient (or via a factory)

Singletons are great when something is:

Expensive to create

Thread-safe

Meant to be shared by everyone

๐Ÿงณ Scoped โ€” โ€œIโ€™m here for this request onlyโ€

Created once per HTTP request.

Shared inside that request.

Destroyed when the request ends.

Think: someone who comes for this party, helps clean up, and goes home.

Good examples: DbContext, Repositories, Business services, Current user / request context

Important detail:

Scoped is not per controller. Itโ€™s per request.

If Controller A and Controller B are part of the same request and both use the same scoped service โ€” they get the same instance.

๐Ÿ‡ Transient โ€” โ€œI just popped in for a secondโ€

New instance every time you ask for it.

Ask twice โ†’ you get two different objects.

No memory. No commitment.

Think: someone who shows up, says hi, disappears, and if you see them againโ€ฆ itโ€™s basically a new person.

Good examples: Helpers, Mappers, Formatters, Small stateless utilities

If you inject a transient service twice in the same constructor:

Surprise! They are not the same object ๐Ÿ˜„

No more confusion. No more lifetime chaos. Now grab a slice ๐Ÿ• โ€” the partyโ€™s just getting started.

Happy DI Pizza Party ๐Ÿ•


๋ฉ”ํƒ€๋ฐ์ดํ„ฐ
post_id
7e70ac066eec
slug
di-lifetimes-in-net-explained-like-a-party-you-actually-want-to-attend-7e70ac066eec
url
https://medium.com/@redwanniloy161293/di-lifetimes-in-net-explained-like-a-party-you-actually-want-to-attend-7e70ac066eec
canonical_url
https://medium.com/@redwanniloy161293/di-lifetimes-in-net-explained-like-a-party-you-actually-want-to-attend-7e70ac066eec
author_url
https://medium.com/@redwanniloy161293
status
ok
fetched_at
2026-07-13 22:23:34