📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

πŸ“š Interview question

What are the singleton, scoped and transient lifetimes in .NET dependency injection? What exactly is a scope in an ASP.NET Core app, and what is it in a worker service where there is no HTTP request?

Covers the three built-in service lifetimes, how the container caches instances for each, what creates and disposes a scope in ASP.NET Core, and why worker services have no scope unless you create one.

Junior Theory Beginner aspnet-core dependency-injection scoped service-lifetimes singleton transient

🎯 Key points

  • Singleton: one instance per root provider, created on first resolve, disposed when the host shuts down
  • Scoped: one instance per IServiceScope; each scope has its own scoped cache and disposal list, singletons are shared from the root
  • Transient: a new instance on every resolve, disposed with the scope (or root) that resolved it
  • ASP.NET Core creates one scope per HTTP request (HttpContext.RequestServices) and disposes it at the end
  • Worker services and BackgroundService have no automatic scope: create one per unit of work with IServiceScopeFactory, not one for the whole loop
  • Scoped resolved from the root provider behaves like a singleton; ValidateScopes throws in Development
  • A service must not depend on one with a shorter lifetime (captive dependency)

⏱ 30-second answer

The lifetime tells the container how long to reuse an instance:

  • Singleton: one instance for the whole app (per root provider), created on first use and disposed when the host stops.
  • Scoped: one instance per scope. In ASP.NET Core the framework creates a scope per HTTP request (HttpContext.RequestServices) and disposes it when the response finishes, so a DbContext is shared by everything in one request.
  • Transient: a new instance every time it is resolved, disposed with the scope that created it.

A worker service has no requests, so there is no scope unless you create one with IServiceScopeFactory.CreateAsyncScope() per message or per loop iteration. The rule that ties it together: a service may only depend on services that live at least as long as it does.

πŸ—£ Full answer (senior)

How I would answer this in an interview

"A lifetime is the container's caching rule. A singleton is created once, the first time someone asks for it, cached in the root provider and disposed when the host shuts down. A scoped service is cached per scope: ask twice inside the same scope and you get the same object, ask in another scope and you get a new one. A transient is never cached: every constructor parameter that asks for it gets a fresh instance.

A scope is just an IServiceScope with its own ServiceProvider and its own list of things to dispose. In ASP.NET Core the hosting layer creates one at the start of every request and puts it on HttpContext.RequestServices; controllers, Minimal API handlers and anything they depend on are resolved from it, and when the request ends the scope is disposed along with every scoped and transient disposable it created. That's why AddDbContext registers the context as scoped: one unit of work per request.

In a worker service there's no request, so nothing creates a scope for you. BackgroundService itself is a singleton. If it needs a DbContext, I inject IServiceScopeFactory and create a scope per message or per iteration, so each unit of work gets fresh scoped services that are disposed when it finishes. The mistake I see is resolving scoped services from the root provider: they never get disposed and quietly become singletons. Lifetime is about who owns the instance and when it dies, not just how many you get."


The three lifetimes

Lifetime Instances Created Disposed Typical use
Singleton 1 per root provider First resolve (or you pass an instance) Host shutdown, if the container created it Caches, IHttpClientFactory, configuration-derived services, stateless thread-safe services
Scoped 1 per scope First resolve in that scope Scope disposal DbContext, unit of work, per-request user context
Transient 1 per resolve Every resolve Disposal of the scope that resolved it Lightweight stateless services, builders

What a scope is in each host

Host Who creates scopes Scope boundary
ASP.NET Core (MVC, Minimal APIs) The framework, per request One HTTP request
SignalR hub The framework, per hub method call One hub invocation
Blazor Server The framework, per circuit The user's connection (can be hours)
Worker service / BackgroundService You, via IServiceScopeFactory Whatever you choose: one message, one batch
Console app / tests You Whatever you choose

The dependency rule

Consumer β†’ dependency OK?
Transient β†’ anything Yes (the transient lives no longer than its consumer's scope)
Scoped β†’ scoped / singleton Yes
Singleton β†’ singleton Yes
Singleton β†’ scoped or transient-disposable No: captive dependency

Production example

In an order API, OrdersDbContext is scoped, so the handler, the repository and the outbox writer in one request share one change tracker and commit in one SaveChangesAsync. The same code in a queue worker created one scope per message; before that fix, a single context lived for the process lifetime, its change tracker grew to [hundreds of thousands of] entities and memory climbed until the pod restarted.

πŸ” What the interviewer is checking

Checks that the candidate knows what each lifetime caches, what a scope actually is, and that worker services need explicit scopes.

Green flags

  • Defines scoped as "per IServiceScope" and says ASP.NET Core creates one per request
  • Mentions disposal, not just instance count
  • Knows BackgroundService is a singleton and needs IServiceScopeFactory
  • States the longer-lived-must-not-depend-on-shorter-lived rule

Red flags

  • "Scoped is per thread" or "per session"
  • Injects DbContext straight into a hosted service
  • No idea when transients are disposed

πŸ“š Learn in depth

1. What the container stores

ServiceCollection is just a list of ServiceDescriptors: service type, implementation (type, factory or instance) and ServiceLifetime. BuildServiceProvider() turns that into a root ServiceProvider that owns:

  • a singleton cache (resolved services keyed by call site),
  • a root scope (ServiceProviderEngineScope) with its own disposables list.

Every CreateScope() makes a new engine scope with an empty scoped cache and its own disposables list.

Root ServiceProvider
 β”œβ”€ singleton cache       (shared by every scope)
 β”œβ”€ root scope disposables
 └─ CreateScope() ─┬─ Scope A: scoped cache, disposables
                   └─ Scope B: scoped cache, disposables

2. Resolving each lifetime

  • Singleton: look in the root cache; if missing, build it (under a lock) and store it.
  • Scoped: look in the current scope's cache; if missing, build and store it there.
  • Transient: always build. If it implements IDisposable or IAsyncDisposable, add it to the current scope's disposables list.

That last point is why a transient disposable resolved from the root lives until the app stops.

3. The request scope in ASP.NET Core

Kestrel accepts request
  β†’ HttpContext created
  β†’ RequestServices = scopeFactory.CreateAsyncScope().ServiceProvider
  β†’ middleware β†’ routing β†’ endpoint (controller / handler resolved here)
  β†’ response completes
  β†’ scope.DisposeAsync(): scoped + transient disposables, reverse creation order

4. Worker services

AddHostedService<T>() registers the hosted service as a singleton. Its constructor runs once, from the root provider. Anything scoped must come from a scope you create:

ExecuteAsync loop
  └─ for each message:
       await using scope = scopeFactory.CreateAsyncScope();
       handler = scope.ServiceProvider.GetRequiredService<IHandler>();
       await handler.HandleAsync(msg, ct);
     (scope disposed β†’ DbContext disposed)

5. Scope validation

With ValidateScopes = true (on by default when the environment is Development), the provider throws if a scoped service is resolved from the root, or if a singleton depends on a scoped service. Production defaults to off, so the bug ships silently unless you enable it everywhere.

Try it yourself

  1. Register three services that each hold Guid Id = Guid.NewGuid(), one per lifetime. Resolve each twice in two scopes and print the ids.
  2. Make the transient implement IDisposable and log in Dispose. Resolve it from the root and from a scope; see which one disposes when.
  3. Resolve a scoped service from app.Services with ValidateScopes on and read the exception message.
  4. Write a BackgroundService that injects a scoped service directly and watch it fail at start-up in Development.

πŸ’» Code

A console demo that prints instance ids per lifetime and shows when disposal happens.

using Microsoft.Extensions.DependencyInjection;

namespace LifetimeDemo;

public abstract class Tracked : IDisposable
{
    public Guid Id { get; } = Guid.NewGuid();
    public void Dispose() => Console.WriteLine($"  disposed {GetType().Name} {Id.ToString()[..8]}");
}

public sealed class SingletonService : Tracked;
public sealed class ScopedService : Tracked;
public sealed class TransientService : Tracked;

public static class Program
{
    public static void Main()
    {
        var services = new ServiceCollection()
            .AddSingleton<SingletonService>()
            .AddScoped<ScopedService>()
            .AddTransient<TransientService>();

        // ValidateScopes catches scoped-from-root and singleton→scoped at resolve time.
        using var root = services.BuildServiceProvider(new ServiceProviderOptions
        {
            ValidateScopes = true,
            ValidateOnBuild = true
        });

        for (var i = 1; i <= 2; i++)
        {
            Console.WriteLine($"Scope {i}");
            using var scope = root.CreateScope();
            var sp = scope.ServiceProvider;

            Console.WriteLine($"  singleton same? {ReferenceEquals(sp.GetRequiredService<SingletonService>(), sp.GetRequiredService<SingletonService>())}"); // True
            Console.WriteLine($"  scoped same?    {ReferenceEquals(sp.GetRequiredService<ScopedService>(), sp.GetRequiredService<ScopedService>())}");       // True (new per scope)
            Console.WriteLine($"  transient same? {ReferenceEquals(sp.GetRequiredService<TransientService>(), sp.GetRequiredService<TransientService>())}"); // False
        } // scoped + both transients disposed here, reverse creation order

        Console.WriteLine("Root disposing");
    } // singleton disposed here
}

The worker-service shape: a scope per unit of work.

namespace Orders.Worker;

public interface IOrderProcessor
{
    Task<int> ProcessPendingAsync(CancellationToken ct);
}

public sealed class OrderWorker(IServiceScopeFactory scopes, ILogger<OrderWorker> logger) : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        using var timer = new PeriodicTimer(TimeSpan.FromSeconds(10));
        while (await timer.WaitForNextTickAsync(stoppingToken))
        {
            // New scope = new DbContext, disposed at the end of the iteration.
            await using var scope = scopes.CreateAsyncScope();
            var processor = scope.ServiceProvider.GetRequiredService<IOrderProcessor>();
            var count = await processor.ProcessPendingAsync(stoppingToken);
            logger.LogInformation("Processed {Count} orders", count);
        }
    }
}

⚠ Common mistakes

  • Mistake: Thinking scoped means "per thread" or "per user". Why it is wrong: A scope is whatever CreateScope() brackets; in ASP.NET Core that is one request, regardless of threads or users. Instead: Describe it as "one instance per IServiceScope" and name who creates the scope.
  • Mistake: Injecting a scoped service (such as a DbContext) into a BackgroundService constructor. Why it is wrong: The hosted service is a singleton, so the scoped service is resolved from the root and lives for ever; Development throws, Production silently shares one context. Instead: Inject IServiceScopeFactory and create a scope per unit of work.
  • Mistake: Creating one scope at the top of ExecuteAsync and looping inside it. Why it is wrong: The scope lives as long as the worker, so its DbContext and transient disposables accumulate exactly as if they were singletons. Instead: One scope per message, batch or timer tick.
  • Mistake: Assuming transient services are always cheap to garbage collect. Why it is wrong: Transient IDisposables are tracked by the scope that resolved them; resolved from the root they are held until shutdown. Instead: Resolve disposable transients inside a scope, or use a factory you dispose yourself.
  • Mistake: Making everything a singleton "for performance". Why it is wrong: Singletons must be thread-safe and cannot depend on scoped services; the allocation saving is usually nanoseconds. Instead: Choose by state and thread safety, not allocation cost.
  • Mistake: Believing the container disposes instances you registered with AddSingleton(instance). Why it is wrong: The container only disposes what it created. Instead: Dispose pre-built instances yourself or register a factory.
  • Mistake: Storing a resolved scoped service in a static field, a cache entry or a message that outlives the request. Why it is wrong: The object is disposed when its scope ends, so later use throws ObjectDisposedException or reads stale state. Instead: Store data (ids, DTOs), never services.
  • Mistake: Resolving services from app.Services at start-up without a scope. Why it is wrong: That is the root provider; scoped services throw in Development and leak elsewhere. Instead: using var scope = app.Services.CreateScope(); for start-up work.

πŸ› Senior insight: trade-offs

The lifetime is really an ownership contract: who creates the object, who is allowed to share it, and who disposes it. Most production DI bugs are a mismatch between that contract and reality: a singleton holding a scoped DbContext, a transient disposable owned by the root, a worker that never creates a scope. When I review registrations I ask two questions per service: is it safe to share across threads, and does it hold something that must be released per unit of work?

Lifetime When it fits Cost When not to
Singleton Stateless or thread-safe shared state, expensive to build Must be thread-safe; can't take scoped deps Holds per-request data or a DbContext
Scoped Per-unit-of-work state, DbContext Needs a scope; meaningless in a root-only console app Used from singletons without a scope
Transient Lightweight, stateless, or needs a fresh instance per consumer Allocation per resolve; disposables tracked by scope Expensive to construct, or disposable resolved from root

I turn on ValidateScopes and ValidateOnBuild in every environment, so lifetime mistakes fail at start-up in CI rather than as memory growth in production.

πŸ”— Follow-ups the interviewer may ask

  1. When: Candidate mentions AddScoped / AddSingleton registration Why: Checks they know the registration API, TryAdd and multiple implementations
    How to answer

    IServiceCollection is just a list of ServiceDescriptors: a service type, an implementation (type, instance or factory delegate) and a lifetime. AddSingleton, AddScoped and AddTransient append to that list.

    • If you register the same service type several times, injecting T gives you the last registration, while injecting IEnumerable<T> gives you all of them in registration order.
    • TryAdd* adds only if nothing is registered for that service type, which is how libraries provide overridable defaults. TryAddEnumerable adds only if that exact implementation isn't already there.
    • Replace swaps the first registration; RemoveAll clears them.

    The trade-off: ordering makes overrides easy but silent, so registration order bugs are easy to write and hard to see.

  2. When: Candidate says a singleton must not depend on a scoped service Why: Checks they can explain the failure mode and the guard rail
    How to answer

    A captive dependency is a shorter-lived service captured by a longer-lived one, usually a scoped DbContext held by a singleton. The scoped instance stops being per-request: in production it is shared across threads (EF's "second operation" exceptions), serves stale data from its identity map, keeps growing its change tracker and is never disposed.

    ValidateScopes = true makes the provider throw when a singleton's graph contains a scoped service or a scoped service is resolved from the root. The host enables it only in Development by default; turn it on everywhere with builder.Host.UseDefaultServiceProvider(o => { o.ValidateScopes = true; o.ValidateOnBuild = true; }). The cost is a small check on resolution and a one-off graph walk at start-up, far cheaper than the outage. Fix by aligning lifetimes, or creating per-operation instances with IDbContextFactory<T> or IServiceScopeFactory.

  3. When: Candidate resolves services from app.Services or IServiceProvider Why: Checks where resolution should happen
    How to answer

    The composition root is the single place where the application's object graph is wired up: in ASP.NET Core, Program.cs and the AddXxx() extension methods it calls. It is the only code that knows about concrete implementations and the container.

    Everything else asks for what it needs through its constructor. If business classes call IServiceProvider.GetService themselves, that is the service locator anti-pattern: their dependencies are hidden from the signature, a missing registration only shows up at run time, and unit tests need a container instead of a couple of fakes. Keeping resolution in the root keeps business code independent of the container, easier to test and easier to maintain. Framework-driven resolution (middleware Invoke parameters, [FromServices], Minimal API parameters) is fine because it is infrastructure acting on your behalf.

↩ Usually asked after

More in Service Lifetimes

Last updated 23 Nov 2026.

🌐 Sangam's Webring

βͺ Previous 🏠 Main Next ⏩
πŸ’¬ Chat with me