"Types of service instances" refers to the lifetimes you choose when registering services with the .NET dependency injection container. There are three. Transient - Registration: services.AddTransient<IReportFormatter, PdfReportFormatter>(); - A brand-new instance is created every time it is injected or resolved. - Use for lightweight, stateless classes. Be careful with heavy objects, because creating many instances wastes memory. Scoped - Registration: services.AddScoped<IOrderRepository, OrderRepository>(); - One instance per scope — in a web application, one per HTTP request. - Use for anything that should share state within a request: DbContext, unit of work, per-request caches, current user information. Singleton - Registration: services.AddSingleton<IFeatureFlags, FeatureFlagCache>(); - Exactly one instance for the life of the application. - Use for shared, thread-safe services: configuration, caches, clients that are expensive to create. You can also register a ready-made instance (services.AddSingleton(new MyOptions())) or a factory method: services.AddScoped<IClock>(sp => new SystemClock()); Things interviewers check: - Understanding that the lifetime must match the state the service holds. - Awareness of captive dependencies: a singleton that depends on a scoped or transient service keeps that dependency alive forever. The fix is to align lifetimes or create a scope with IServiceScopeFactory when needed. - Knowing that singletons must be thread-safe and must never hold data for a single user. - Knowing that the container calls Dispose on services it created when their lifetime ends. Newer additions: keyed services in .NET 8 (AddKeyedScoped("name")) for multiple implementations of the same interface, and TryAdd methods to avoid duplicate registrations in libraries.
Ravindra Wadile · · 0 likes