The DI container in ASP.NET Core supports three lifecycles, which decide when an instance is created and when it is disposed. Transient — AddTransient<TService, TImpl>() - Created: each time it is resolved. - Disposed: when the scope that resolved it ends. - Example: a stateless SlugGenerator or a validator. Scoped — AddScoped<TService, TImpl>() - Created: once per scope; ASP.NET Core opens a scope per HTTP request. - Disposed: when the request ends. - Example: AppDbContext, a UnitOfWork, a CurrentUserAccessor that caches claims for the request. Singleton — AddSingleton<TService, TImpl>() - Created: the first time it is requested (or immediately if you pass an instance). - Disposed: when the application shuts down. - Example: an in-memory feature-flag cache, IConnectionMultiplexer for Redis, configuration readers. How to reason about it in an interview: start from the state the service holds. - No state: transient or singleton (singleton avoids repeated allocation if the type is thread-safe). - State that belongs to one request or depends on DbContext: scoped. - Shared state or expensive initialisation: singleton, and make it thread-safe. Typical bugs: - Singleton depending on scoped: the scoped instance is captured for the app's lifetime — stale data and concurrency exceptions. - Using a scoped service outside a request (hosted service, Startup code) throws because there is no scope; create one with IServiceScopeFactory.CreateScope(). - Transient disposables resolved from the root provider are kept until shutdown. ASP.NET Core validates these mistakes when ValidateScopes is enabled (the default in Development). Enabling ValidateOnBuild also checks that every registered service can be constructed at startup.
Ravindra Wadile · · 0 likes