How remononnorokom/di_service_lifetime works
Main Components
a. Composition Root
• This is the entry point (e.g. Program.cs or Startup.cs) where you build the IServiceCollection and call BuildServiceProvider().
b. DI Container (ServiceProvider)
• The container that holds registrations and resolves instances.
c. Services with Different Lifetimes
• TransientService (registered with AddTransient<T>)
• ScopedService (registered with AddScoped<T>)
• SingletonService (registered with AddSingleton<T>)
d. Consumer(s) / Client(s)
• Classes (e.g. controllers, console commands) that request those services.
e. (If Web API) HTTP Request Pipeline
• Scope creation per incoming request.
f. (If Console) Manual Scope / Using IServiceScopeFactory
Relationships and Data Flows
• The Composition Root ➔ registers all services with distinct lifetimes.
• At runtime the ServiceProvider ➔ resolves services
• Transient: new instance every time it’s requested
• Scoped: one instance per scope (e.g. per HTTP request or per manually created scope)
• Singleton: one instance for the entire container lifetime
• Consumer(s) depend on these services via constructor injection.
Important Architectural Patterns
• Inversion of Control (IoC) / Dependency Injection
• Lifetime management as a cross-cutting concern
• If Web API, the scoped lifetime aligns with the request pipeline pattern