⏳ The 3 Lifetimes
-
🔵 Singleton → stateless global services
-
🟢 Scoped → per-request (web default)
-
🟠 Transient → lightweight, multi-instance
❌ Absolute Rule
Never inject a Scoped service into a Singleton.
Bad:
builder.Services.AddSingleton<MyService>(); // depends on DbContext ❌
✔ Correct
Use factory:
builder.Services.AddSingleton<MyService>(sp =>
new MyService(sp.GetRequiredService<IDbContextFactory<AppDb>>()));
🧠 Why?
-
Prevents stale data
-
Eliminates threading issues
-
Perfect for background workers
