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.
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.
"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
DbContextit depends on. Singletons belong to the root, so they go when the host shuts down. If I register an instance I built myself withAddSingleton(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
IDisposablethe scope that resolved it holds a reference until the scope ends. Resolve one from the root provider, say inside a singleton's factory or withapp.Services.GetRequiredServiceon 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 byServiceProviderEngineScope._disposables.For async, the container understands
IAsyncDisposable.DisposeAsyncon a scope awaitsDisposeAsyncon each service. But if a service implements onlyIAsyncDisposableand something disposes the scope synchronously, the provider throws anInvalidOperationExceptiontelling you to useDisposeAsync. That's why I useCreateAsyncScope()andawait usingin workers. The mistake I see is code callingDispose()on an injected dependency: you don't own it, other consumers in the same scope may still be using it."
| 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 |
| Service implements | Scope Dispose() |
Scope DisposeAsync() |
|---|---|---|
IDisposable |
Dispose |
Dispose |
| Both | Dispose |
DisposeAsync |
Only IAsyncDisposable |
Throws InvalidOperationException |
DisposeAsync |
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].
Checks that the candidate understands container ownership of disposables, the root-tracked transient leak and async disposal rules.
Green flags
AddSingleton(instance) is not disposedDispose of an async-only service throws, uses CreateAsyncScopeRed flags
Dispose on injected servicesEvery 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.
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.
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.
AddSingleton<IFoo>(new Foo()): not disposed.AddSingleton<IFoo>(sp => new Foo()): disposed (the container invoked the factory).new: the service owns them and should dispose them in its own Dispose.IDbContextFactory<T>.CreateDbContext(): the caller owns them.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.
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.IAsyncDisposable, create a scope with using and observe the exception; switch to await using CreateAsyncScope().dotnet-gcdump collect -p <pid>; inspect what roots the objects.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>();
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.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.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();.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.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.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.
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.
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.
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.
Last updated 23 Nov 2026.