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

📚 Interview question

Who disposes the services the .NET container creates? Explain when singleton, scoped and transient disposables are disposed, what happens to a transient IDisposable resolved from the root provider, how IAsyncDisposable is handled, and in what order disposal happens.

Covers container ownership of IDisposable and IAsyncDisposable services: disposal per lifetime, root-tracked transient disposables, the sync-dispose-of-async-only-service exception, instances the container does not own, and reverse-order disposal.

Mid-Level Theory Intermediate dependency-injection iasyncdisposable idisposable memory-leaks service-lifetimes

🎯 Key points

  • The container disposes only services it created; instances passed to AddSingleton(instance) are yours
  • Each scope keeps a list of disposables it created (scoped and transient) and disposes them when the scope ends
  • Singletons are disposed when the root provider is disposed (host shutdown)
  • Transient IDisposable resolved from the root is tracked until shutdown; resolved repeatedly (per call or per request) it becomes a leak
  • Disposal runs in reverse order of creation, so consumers go before their dependencies
  • IAsyncDisposable: always dispose scopes with await DisposeAsync (CreateAsyncScope + await using); synchronous Dispose of a scope holding an async-only service throws InvalidOperationException
  • Never call Dispose on an injected service; do dispose objects your own code creates with new or a factory

⏱ 30-second answer

The container owns and disposes what it creates. Each scope keeps a list of the IDisposable/IAsyncDisposable objects it built (scoped and transient) and disposes them, in reverse creation order, when the scope ends; singletons are disposed when the root provider is disposed at host shutdown. Instances you pass in with AddSingleton(instance) are not disposed by the container.

The trap: a transient disposable resolved from the root is tracked by the root, so it lives until shutdown, which is a memory leak if it happens per request. For async: disposing a scope with DisposeAsync calls DisposeAsync on services; calling synchronous Dispose on a scope that holds a service implementing only IAsyncDisposable throws. So use CreateAsyncScope() with await using, and never dispose injected services yourself.

🗣 Full answer (senior)

How I would answer this in an interview

"The rule is ownership: whoever creates it disposes it, and for container-built services that's the container. Every scope, including the root, keeps a list of disposables it created. When a request scope ends, ASP.NET Core disposes it and every scoped and transient disposable built in that scope is disposed in reverse order, so a repository is disposed before the DbContext it depends on. Singletons belong to the root, so they go when the host shuts down. If I register an instance I built myself with AddSingleton(instance), the container won't dispose it, because it didn't create it.

The surprising part is transients. People assume a transient is fire-and-forget, but if it implements IDisposable the scope that resolved it holds a reference until the scope ends. Resolve one from the root provider, say inside a singleton's factory or with app.Services.GetRequiredService on every call, and the root keeps every instance until the process exits. I've seen that look exactly like a classic memory leak in a dump: thousands of objects rooted by ServiceProviderEngineScope._disposables.

For async, the container understands IAsyncDisposable. DisposeAsync on a scope awaits DisposeAsync on each service. But if a service implements only IAsyncDisposable and something disposes the scope synchronously, the provider throws an InvalidOperationException telling you to use DisposeAsync. That's why I use CreateAsyncScope() and await using in workers. The mistake I see is code calling Dispose() on an injected dependency: you don't own it, other consumers in the same scope may still be using it."


Who disposes what

Service Disposed by When
Singleton built by the container Root provider Host shutdown
Singleton passed as an instance You Whenever you decide
Scoped Its scope Scope end (end of request)
Transient resolved in a scope That scope Scope end, not when you finish with it
Transient resolved from root Root provider Host shutdown (leak risk)
Object from your own factory method you call yourself You using / await using

Sync and async disposal

Service implements Scope Dispose() Scope DisposeAsync()
IDisposable Dispose Dispose
Both Dispose DisposeAsync
Only IAsyncDisposable Throws InvalidOperationException DisposeAsync

Production example

A reporting service resolved a transient PdfRenderer (wrapping a native handle) from app.Services inside a static helper on every report. Memory grew by [about 40 MB an hour] until the pod was OOM-killed every [two days]. A dotnet-gcdump showed [~90,000] renderers rooted by the root scope's disposables list; resolving them inside a request scope instead flattened memory at [~350 MB].

🔍 What the interviewer is checking

Checks that the candidate understands container ownership of disposables, the root-tracked transient leak and async disposal rules.

Green flags

  • "The container disposes what it creates" and knows AddSingleton(instance) is not disposed
  • Explains transient disposables are tracked by the resolving scope, and the root leak
  • Knows sync Dispose of an async-only service throws, uses CreateAsyncScope
  • Mentions reverse creation order

Red flags

  • Calls Dispose on injected services
  • Thinks transients are disposed immediately after use
  • Unaware the root provider is a scope with its own disposables

📚 Learn in depth

1. The disposables list

Every ServiceProviderEngineScope (the root provider has one too) holds a List<object> of disposables. When the call-site resolver builds an instance whose type implements IDisposable or IAsyncDisposable, it calls CaptureDisposable, which adds it to the current scope's list.

Request scope
  resolve OrderHandler (transient, IDisposable)  → _disposables[0]
    resolve OrderRepository (scoped, IDisposable) → _disposables[1]? (built first)
      resolve AppDbContext (scoped)               → built first of all
Scope end → dispose list from last to first

Dependencies are constructed before their consumers, so they're captured first and disposed last: consumers are always disposed before what they depend on.

2. Why transients leak from the root

The root scope never ends until the host does. Each transient disposable resolved from it is added to the root list, so the GC can never collect it:

GC root → ServiceProvider → Root ServiceProviderEngineScope → _disposables → [PdfRenderer x 90,000]

ValidateScopes does not catch this; it's legal, just wasteful.

3. Async disposal

ServiceProviderEngineScope implements both IDisposable and IAsyncDisposable:

  • DisposeAsync(): for each captured object (reverse order), prefer IAsyncDisposable.DisposeAsync(), else Dispose().
  • Dispose(): for each object, call Dispose() if it implements IDisposable; if it implements only IAsyncDisposable, throw InvalidOperationException ("'X' type only implements IAsyncDisposable. Use DisposeAsync to dispose the container.").

ASP.NET Core disposes request scopes asynchronously, and the generic host disposes the root asynchronously, so this mostly bites in tests, console apps and workers using CreateScope() with using.

4. What the container does not own

  • AddSingleton<IFoo>(new Foo()): not disposed.
  • AddSingleton<IFoo>(sp => new Foo()): disposed (the container invoked the factory).
  • Objects created inside a service with new: the service owns them and should dispose them in its own Dispose.
  • Objects returned from IDbContextFactory<T>.CreateDbContext(): the caller owns them.

5. Disposal and lifetimes interacting

A singleton holding a scoped disposable will keep using it after its scope disposed it: ObjectDisposedException. That is the captive-dependency bug seen through the disposal lens.

Try it yourself

  1. Register a transient IDisposable that logs in Dispose; resolve it 10 times in a scope and 10 times from the root; dispose the scope and count log lines.
  2. Register a service implementing only IAsyncDisposable, create a scope with using and observe the exception; switch to await using CreateAsyncScope().
  3. Resolve a transient disposable from the root in a loop of 100,000 and take dotnet-gcdump collect -p <pid>; inspect what roots the objects.
  4. Log construction and disposal order for a three-level graph and confirm reverse order.

💻 Code

Disposal order, root leaks and async disposal in one console app.

using Microsoft.Extensions.DependencyInjection;

namespace DisposalDemo;

public sealed class Connection : IDisposable
{
    public Connection() => Console.WriteLine("create Connection");
    public void Dispose() => Console.WriteLine("dispose Connection");
}

public sealed class Repository(Connection connection) : IDisposable
{
    public void Dispose() => Console.WriteLine("dispose Repository"); // runs before Connection
}

public sealed class AsyncOnlyExporter : IAsyncDisposable
{
    public ValueTask DisposeAsync()
    {
        Console.WriteLine("dispose AsyncOnlyExporter (async)");
        return ValueTask.CompletedTask;
    }
}

public static class Program
{
    public static async Task Main()
    {
        var services = new ServiceCollection()
            .AddScoped<Connection>()
            .AddTransient<Repository>()
            .AddScoped<AsyncOnlyExporter>();

        await using var root = services.BuildServiceProvider(validateScopes: true);

        // Correct: async scope, disposed in reverse creation order.
        await using (var scope = root.CreateAsyncScope())
        {
            _ = scope.ServiceProvider.GetRequiredService<Repository>();
            _ = scope.ServiceProvider.GetRequiredService<AsyncOnlyExporter>();
        }

        // Wrong: sync dispose of a scope holding an async-only service throws.
        try
        {
            using var scope = root.CreateScope();
            _ = scope.ServiceProvider.GetRequiredService<AsyncOnlyExporter>();
        }
        catch (InvalidOperationException ex)
        {
            Console.WriteLine($"sync dispose failed: {ex.Message}");
        }
    }
}

When you need a disposable per operation from a singleton, own it explicitly instead of resolving transients from the root:

namespace Reports;

public sealed class PdfRenderer : IDisposable
{
    public byte[] Render(string html) => [];
    public void Dispose() { /* release native handle */ }
}

public sealed class ReportService(Func<PdfRenderer> createRenderer)
{
    public byte[] Build(string html)
    {
        using var renderer = createRenderer(); // caller owns and disposes it
        return renderer.Render(html);
    }
}

// Program.cs
// services.AddSingleton<Func<PdfRenderer>>(() => new PdfRenderer()); // not tracked by the container
// services.AddSingleton<ReportService>();

⚠ Common mistakes

  • Mistake: Calling Dispose() on a constructor-injected service. Why it is wrong: You don't own it; other consumers in the same scope (or every request, for a singleton) may still use it. Instead: Let the container dispose services it resolved for you. Objects your own code creates with new or from a factory are yours: dispose those with using.
  • Mistake: Resolving transient disposables from IServiceProvider/app.Services in a singleton or static helper on every call. Why it is wrong: The root tracks each one until shutdown, so memory grows per call. Instead: Resolve inside a scope, or use a factory delegate whose result you dispose with using.
  • Mistake: Assuming a transient is disposed when the consumer finishes with it. Why it is wrong: It is disposed when its scope ends; in a long-lived scope (Blazor circuit, worker loop scope) that may be hours. Instead: Keep scopes short or own the object explicitly.
  • Mistake: Using CreateScope() with using when services implement only IAsyncDisposable. Why it is wrong: Synchronous disposal throws InvalidOperationException, and for services implementing both it skips the async path (blocking flushes on a thread-pool thread). Instead: await using var scope = factory.CreateAsyncScope();.
  • Mistake: Registering a pre-built disposable with AddSingleton(instance) and expecting cleanup. Why it is wrong: The container did not create it, so it will not dispose it. Instead: Use a factory registration or dispose it in IHostApplicationLifetime.ApplicationStopped.
  • Mistake: Doing slow I/O in Dispose (flushing to a remote service). Why it is wrong: It blocks the request thread at scope end, reducing throughput under load, and can delay shutdown. Instead: Implement IAsyncDisposable and flush in DisposeAsync.

🏛 Senior insight: trade-offs

Disposal is where lifetime mistakes become visible: leaks, ObjectDisposedException and shutdown hangs. The question I ask in review is "who owns this object, and when does that owner die?" If the answer is "the root provider" for something created per operation, it's a leak regardless of what the lifetime says. I also prefer IAsyncDisposable for anything that flushes or closes network resources, because ASP.NET Core and the host dispose asynchronously and blocking there costs thread-pool threads at shutdown.

Pattern When it fits Cost When not to
Let the scope dispose (scoped / transient in scope) Normal request and per-message work Lives until scope end Very long-lived scopes with many transients
Factory (Func<T>, IDbContextFactory<T>) and using Per-operation resources from singletons Caller must remember to dispose When a scoped service would do
IServiceScopeFactory per operation Several scoped services needed together Slight service-locator smell Single dependency (use a factory)
AddSingleton(instance) Pre-configured objects you manage You dispose it Disposable objects you forget about

To measure: dotnet-counters for GC heap size trend, then dotnet-gcdump and look for ServiceProviderEngineScope as the retention path.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions finalisers or the dispose pattern Why: Checks the relationship between IDisposable, finalisers and SafeHandle
    How to answer

    C# has finalisers, written with destructor syntax ~MyType(), but they are not C++ destructors. The compiler turns them into an override of Object.Finalize. The GC calls them at some unknown time after the object becomes unreachable, on a single finaliser thread, in no guaranteed order, and possibly never (for example at process exit in .NET Core and later). Objects with finalisers cost more: they are tracked from allocation, survive at least one extra GC and get promoted. For deterministic clean-up use IDisposable with using. Only classes that directly own unmanaged resources need a finaliser, and even then wrap the handle in a SafeHandle, which has the finaliser for you. The full dispose pattern (Dispose(bool) plus GC.SuppressFinalize) is for unsealed classes that may hold unmanaged state.

  2. When: Candidate mentions transient disposables resolved from the root Why: Checks they can recognise the root-tracked transient leak in a dump
    How to answer

    The container is keeping objects alive because it promised to dispose them. Every scope, including the root, tracks the transient IDisposables it creates until the scope ends; for the root that means process shutdown. Typical causes are resolving from app.Services or from an IServiceProvider injected into a singleton (which is the root), or a scope created once and never disposed. ValidateScopes doesn't catch it.

    Find the type and call site from the gcdump's retention path (ServiceProviderEngineScope → disposables), then either create a scope per operation with IServiceScopeFactory.CreateAsyncScope() when several scoped services are needed, or use a factory whose result you dispose with using when it's one object. The cost of leaving it: a growing Gen2 heap, longer full GCs and eventual OOM kills. Verify with dotnet-counters over several hours.

🛠 Real-world problems: how you handle them

Transient PDF renderers rooted by the root provider leaked 40 MB an hour
Situation
[Document generation API on Azure Kubernetes Service, Australia Southeast, about 30,000 reports a day]. A static ReportHelper resolved a transient PdfRenderer (wrapping a native handle) from app.Services for each report.
Signals
Pods OOM-killed every [two days]; working set grew steadily [~40 MB an hour] regardless of traffic shape; GC heap size in dotnet-counters climbed and never dropped after Gen2 collections.
Investigation
Ran dotnet-counters monitor to confirm managed heap growth, then dotnet-gcdump collect on a pod and opened it in Visual Studio. The largest retained type was PdfRenderer [~90,000 instances], retention path ServiceProvider → ServiceProviderEngineScope (root) → _disposables. Searching the code for GetRequiredService<PdfRenderer> found the static helper using the root provider.
Resolution
Immediate: raised the memory limit and scheduled a rolling restart to buy time. Real fix: removed the static helper; ReportService now takes Func<PdfRenderer> registered as a singleton factory and disposes each renderer with using, so the container no longer tracks them.
Prevention
Banned IServiceProvider in non-composition code with a BannedApiAnalyzers entry for app.Services usage outside Program.cs; added a memory soak test in CI that renders 10,000 reports and asserts heap growth under [50 MB]; alert on working-set slope in Azure Monitor.

How to tell it (STAR)

**S:** At [company], our document API's pods were being OOM-killed every [two days], and it had become a [weekly on-call page]. **T:** I was asked to find the leak rather than keep raising memory limits. **A:** dotnet-counters showed the managed heap growing about [40 MB an hour], so I took a gcdump. Ninety thousand PdfRenderer objects were held by the root service provider's disposables list. A static helper resolved this transient disposable from app.Services, so the root kept every one until shutdown. I replaced it with an explicit factory and using, banned root-provider access outside Program.cs with an analyser rule, and added a soak test. **R:** Memory flattened at [about 350 MB], the OOM restarts stopped completely, and the soak test has caught [one] similar regression since.

↩ Usually asked after

More in Service Lifetimes

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me