"Dependency pattern" here means dependency injection, and the lifetimes are transient, scoped and singleton. Transient — new every time - Each resolution creates a new object. - Lifetime ends when the scope that resolved it is disposed. - Use for stateless, lightweight services. Scoped — one per request - One object per scope; in ASP.NET Core a scope equals one HTTP request. - Shared by every class that participates in the same request. - Use for DbContext, repositories, unit of work and request context. Singleton — one per application - Created on first use and reused until the application stops. - Must be thread-safe and must not keep per-user state. - Use for caches, configuration, logging infrastructure and shared clients. How a request uses them — picture a request to an OrdersController: - The controller receives OrderService (scoped), which uses AppDbContext (scoped) and IClock (singleton), and creates validators (transient). - Within this request, any other class asking for OrderService receives the same instance; a second request gets a new OrderService and a new DbContext, but the same IClock. - At the end of the request, the scope is disposed and so are the scoped and transient disposables it created. The golden rule: dependencies must live at least as long as their consumer. A singleton must not hold a scoped object (captive dependency); this produces stale data and threading bugs. ASP.NET Core detects it in Development with scope validation. Tip for interviews: mention how you chose a lifetime for a specific service in your project, and why. That shows practical understanding rather than memorised definitions.
Ravindra Wadile · · 0 likes