The built-in .NET DI container offers three service lifetimes. 1. Transient — services.AddTransient<IMyService, MyService>() A new instance each time the service is requested. If two classes in the same request both need it, each gets its own instance. 2. Scoped — services.AddScoped<IMyService, MyService>() One instance per scope. ASP.NET Core creates one scope per HTTP request, so all consumers during that request share the instance. A new request gets a new instance. 3. Singleton — services.AddSingleton<IMyService, MyService>() One instance for the entire lifetime of the application, shared by all requests and threads. Typical choices: - DbContext: scoped (registered by AddDbContext). - Repositories and unit-of-work classes: scoped, because they depend on DbContext. - Configuration, caches, HttpClient factories, logging: singleton. - Stateless helpers and validators: transient. The main rule — the captive dependency problem: A service must not depend on a service with a shorter lifetime. If a singleton receives a scoped DbContext through its constructor, that DbContext is captured and lives for the whole app, causing stale data, memory growth and threading errors. ASP.NET Core detects this in the Development environment and throws an exception at startup or resolution. Other details: - Singletons must be thread-safe. - The container disposes IDisposable services automatically at the end of their lifetime. - Outside a request (for example in a BackgroundService), create a scope with IServiceScopeFactory to use scoped services. - Starting with .NET 8, keyed services allow several registrations of the same interface distinguished by a key, with the same three lifetimes. A quick way to demonstrate: generate a GUID in the constructor of each service and log it across two requests to see which instances are reused.
Ravindra Wadile · · 0 likes