skip to content

In ASP.NET Core, why does resolving IDisposable transient services from app.Services grow memory, and which instances does the container never dispose?

level: seniorimportance: should knowfreq 34%

answer

  1. container disposes what it creates
  2. tracked by the resolving scope
  3. root scope ends at shutdown
  4. AddSingleton(instance) is yours
  5. reverse order of creation

basics

~20 s

The container tracks every disposable it builds in the resolving scope; the root scope behind app.Services lasts until shutdown, so root-resolved disposable transients pile up. Instances you pass in, as in AddSingleton(new X()), are never disposed by the container.

solid answer

~50 s

The built-in container remembers every `IDisposable` or `IAsyncDisposable` object it creates, in the scope that resolved it (singletons in the root), so it can dispose it when that scope ends. `app.Services` is the **root** scope and ends only at host shutdown, so each disposable transient resolved from it, for example in a loop or a singleton's timer, stays referenced until then: a leak that a heap dump shows rooted in the container. A scoped service resolved from the root is, with validation off, kept for the app's lifetime, which is why `ValidateScopes` rejects it. The container never disposes an instance it did not create: one registered with `AddSingleton<IQuoteFeed>(new QuoteFeed())`, or anything you construct with `new`. It does dispose objects returned by factory lambdas. Disposal runs in reverse order of creation; the fix for the leak is to resolve inside a scope.

code

csharp · 12 lines
csharp
// Disposed by the container at shutdown (it built them):
builder.Services.AddSingleton<IQuoteFeed, QuoteFeed>();
builder.Services.AddSingleton<IMarketClock>(sp => new MarketClock());

// NOT disposed by the container (you built it):
builder.Services.AddSingleton<ITickArchive>(new TickArchive("ticks.bin"));

var app = builder.Build();

// Leaks until shutdown if ICsvExport is a disposable transient:
for (var i = 0; i < 10_000; i++)
    app.Services.GetRequiredService<ICsvExport>().Write(i);

go deeper

for a junior

Remember that the DI container disposes services it created when their scope ends, and that you never dispose injected services yourself.

for a middle

Explain why the root scope keeps root-resolved disposables until shutdown and why AddSingleton with a ready-made instance is not disposed by the container.

for a senior

Diagnose a steady memory climb back to service location on app.Services, prove it from a dump, and fix it with scopes or an owned-instance factory.

for a principal

Decide how the codebase bans service location in hot paths and which disposable types may be transient, so leaks are prevented by design rather than found in dumps.

## Disposal is tracked per scope The built-in container (`Microsoft.Extensions.DependencyInjection`) follows one rule: **it disposes what it creates, when the scope that created it ends.** Every time it builds an object that implements `IDisposable` or `IAsyncDisposable`, it appends that object to a list kept by the scope that performed the resolution (by the root scope, for singletons). When the scope is disposed, it walks the list in **reverse order of creation**, so a service goes before the dependencies it was built from. | Resolved from | Kept until | Typical example | |---|---|---| | a request scope | the response completes | services injected into a controller or handler | | a scope you created | your `await using` block ends | `IServiceScopeFactory.CreateAsyncScope()` work | | the root scope (`app.Services`) | the host shuts down | singletons, and anything else resolved from the root | ## The leak: disposable transients from the root The root scope lives as long as the process. Consider a singleton in a stock-trading dashboard that formats a report every few seconds: ```csharp public class TickerReporter(IServiceProvider services) // the root provider { public void Tick() { var export = services.GetRequiredService<ICsvExport>(); // transient, IDisposable export.Write(/* ... */); } // export is never released: the root scope still references it } ``` Each call creates a new `CsvExport`, and the root scope adds it to its disposal list. Nothing removes it until shutdown, so memory grows steadily and objects holding buffers or handles accumulate. A heap dump shows thousands of instances kept alive by the container rather than by your code. Calling `export.Dispose()` yourself releases its resources but **not** the reference, so the memory still grows. Fixes: 1. **Resolve inside a scope**, so the scope releases and disposes the object at the end of the unit of work: ```csharp public class TickerReporter(IServiceScopeFactory scopes) { public async Task TickAsync() { await using var scope = scopes.CreateAsyncScope(); var export = scope.ServiceProvider.GetRequiredService<ICsvExport>(); export.Write(/* ... */); } } ``` 2. **Do not register short-lived disposables as transient services** when callers need to control their lifetime; register a factory service that returns new instances the caller owns and disposes. 3. If the object is stateless and thread-safe, make it a singleton and stop creating it at all. ## Scoped services resolved from the root When `ValidateScopes` is off, which is every non-Development environment by default, asking `app.Services` for a scoped service does not fail: the container treats the root scope as the scope and caches the object there, so it behaves like a singleton until shutdown. With validation on, the same call throws "Cannot resolve scoped service 'TradingDbContext' from root provider." That is why startup code that needs a scoped service opens a scope first. ## What the container never disposes - **Instances you hand it.** `builder.Services.AddSingleton<IQuoteFeed>(new QuoteFeed())` registers a ready-made object. The container did not create it, so it does not dispose it, even at shutdown. If it holds a socket or a timer, you dispose it yourself, for example from an `IHostApplicationLifetime.ApplicationStopping` callback. - **Objects you create with `new`** inside your services, or receive from elsewhere. By contrast, registering `AddSingleton<IQuoteFeed, QuoteFeed>()` or `AddSingleton<IQuoteFeed>(sp => new QuoteFeed(...))` lets the container build the object, so it is tracked and disposed when the host stops. Objects returned by factory lambdas are treated the same as constructor-built ones: if the result is disposable, the resolving scope disposes it. ## Diagnosing it in production - Memory grows with time or traffic, not with data size, and does not fall after a garbage collection. - A dump shows many instances of one disposable type, each referenced from the container's root scope rather than from application code. - The `Microsoft-Extensions-DependencyInjection` event source reports, for each disposed scope, how many services and disposables it held, which helps confirm where resolutions happen. - Code review finds `app.Services` or an injected root `IServiceProvider` used as a service locator in a hot path. ## Why the rule is per scope Tracking by the resolving scope is what makes request-scoped disposal work: everything a request created is released when its scope ends, without the application tracking anything. The cost of that design is the root case. The container cannot know that a root-resolved transient is no longer used, because it never sees the last reference go away, so it holds the object until the only moment it is sure about: shutdown. ## Summary for the interview The scope that resolves an object owns its disposal; the root scope ends only at shutdown, so disposable transients resolved there leak; scoped services resolved there become app-lifetime; and instances you pass in are your responsibility.

  • Does calling Dispose() on the transient yourself stop the leak?
    It frees the object's own resources but not the memory: the root scope still holds a reference in its disposal list until shutdown, and it will call `Dispose` again then. The real fix is to resolve inside a scope created with `IServiceScopeFactory`, or to stop registering a short-lived disposable as a transient service.
  • Why can resolving a disposable from a scope that has already been disposed throw?
    After disposal the scope refuses further resolutions with `ObjectDisposedException`. If a resolution races with disposal, the container disposes the newly built object at once and then throws, so nothing is created that would never be disposed.

  • Disposable transients are never tracked, so the garbage collector handles them.
  • Calling Dispose() on a root-resolved transient frees its memory.
  • The container disposes a singleton registered as AddSingleton(new X()) at shutdown.
  • Scoped services resolved from app.Services are disposed after the call returns.
  • Disposal happens in the order services were created.