Service lifetimes define how long objects created by the .NET dependency injection container live and how often they are reused. 1. Transient — AddTransient<IService, Service>() - A new instance every time the service is requested. - Best for lightweight, stateless services (formatters, validators, small helpers). - Instances are disposed when the scope that created them ends. 2. Scoped — AddScoped<IService, Service>() - One instance per scope. In ASP.NET Core, a scope is created for each HTTP request, so all classes in the same request share the instance. - Best for request-specific state and units of work: EF Core DbContext, repositories, the current user or tenant context. - Disposed at the end of the request. 3. Singleton — AddSingleton<IService, Service>() - One instance for the whole application lifetime, shared by all requests and threads. - Best for thread-safe shared services: configuration, caches, logging infrastructure, expensive clients (for example a Redis connection multiplexer). - Disposed when the application shuts down. Example builder.Services.AddDbContext<AppDbContext>(...); // scoped by default builder.Services.AddScoped<IOrderService, OrderService>(); builder.Services.AddTransient<IPriceFormatter, PriceFormatter>(); builder.Services.AddSingleton<IFeatureFlags, CachedFeatureFlags>(); Rules for choosing - Ask what state the service holds and whether it is thread-safe. - A service must not depend on a service with a shorter lifetime. A singleton that receives a scoped DbContext "captures" it for the app's lifetime (captive dependency), causing threading errors and stale data. ASP.NET Core detects this in Development. - Singletons must never store per-user or per-request data. - In background services (which are singletons), create scopes with IServiceScopeFactory to use scoped services. Extras worth mentioning - Keyed services (.NET 8+) for multiple implementations of the same interface. - TryAdd methods to avoid duplicate registrations in libraries. - ValidateOnBuild and ValidateScopes to catch configuration mistakes at startup.
Ravindra Wadile · · 0 likes