wasAsked.

What is Scoped lifetime, and where have you used it before?

Impetus · Role not specified · technical

Published

Year not specified · Software Engineering

Community answers

Posted by wasAsked editorial collection

A scoped lifetime means the dependency injection container creates one instance per scope. In ASP.NET Core, the framework creates a scope for each HTTP request, so every class that needs the service during that request receives the same instance, and a new instance is created for the next request. Scoped services are disposed when the request ends. Registration builder.Services.AddScoped<IOrderService, OrderService>(); builder.Services.AddDbContext<AppDbContext>(...); // DbContext is scoped by default Where I have used it (typical real examples) 1. EF Core DbContext and repositories The DbContext is scoped so that all repositories and services in one request share the same context and change tracker. This allows one SaveChanges call to save related changes from several services in a single transaction, and it avoids thread-safety issues because DbContext is not designed for concurrent use. 2. Unit of work and application services OrderService, InvoiceService and other services depending on DbContext are scoped too, since a service must not live longer than its dependencies. 3. Request context services A CurrentUser or TenantContext service that reads claims from HttpContext once and is reused by the rest of the request — for example to apply tenant filters in queries and to stamp CreatedBy fields. public sealed class TenantContext(IHttpContextAccessor accessor) : ITenantContext { public string TenantId { get; } = accessor.HttpContext?.User.FindFirst("tenant_id")?.Value ?? throw new UnauthorizedAccessException(); } 4. Per-request caching Caching data that is expensive to compute and needed by several components in the same request, without sharing it across users. Things to watch - Never inject a scoped service into a singleton (captive dependency): it would be captured for the application's lifetime, causing stale data and concurrency errors. - Background services and singletons that need scoped services must create a scope explicitly: using var scope = scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService<AppDbContext>(); - Scoped services are not thread-safe by default; avoid using them from parallel tasks within the same request. - In Blazor Server, a scope lasts for the whole user circuit, not a single request — an important difference.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics