skipnothing/.NET Platform

Service Lifetimes

You change `AddScoped` to `AddSingleton` to stop rebuilding the same object, the app still runs, and three requests later one user sees another user's data. One word on a registration decided that.

  • Swap one keyword, AddScoped for AddSingleton, and the same IClock goes from per-request to forever.
  • Put a short-lived object inside a long-lived one and it freezes at the wrong moment, no error.
  • Resolve the wrong disposable from the wrong place and it never dies until your whole app does.
BUILDS ON
01

Pick the lifetime, change the reuse

Every registration you wrote in the last topic carried a third value you ignored: its lifetime. services.AddSingleton<IClock, SystemClock>(), AddScoped, AddTransient, three methods, same shape, one word different. That word answers a single question the container asks on every GetRequiredService<IClock>() call: build a new SystemClock, or hand back one it already has?

Call it with AddTransient and every resolve builds a brand-new instance. Call it with AddScoped and the container hands back one instance per web request, then a fresh one for the next request. Call it with AddSingleton and you get the exact same instance for the life of the process. Nothing else about the registration changes. The service type, the implementation type, the constructor graph the container walks, all identical. Only the reuse policy moves.

Watch the count, find the bug, learn the cleanup. The rest of this topic is what happens when that one word is wrong.

SAME REGISTRATION, THREE REUSE POLICIES

Keep going, sign up to unlock the rest

3 more parts in this topic, plus 25+ more topics in .NET Platform.

Sign up, it's freeSee the full .NET Platform
Dependency Injection0/6#13 The .NET DI Container
#15 Registration Patterns