How does the DI container's disposal behavior work for IDisposable services registered as Transient, and why can this cause unexpected memory retention?
Short answer
The DI container automatically tracks and disposes any IDisposable/IAsyncDisposable service it created, calling Dispose when the owning scope ends -- notably, Transient services are still tracked and disposed by their containing scope, not immediately after use, meaning many…
Advertisement
AModel answer
The DI container automatically tracks and disposes any IDisposable/IAsyncDisposable service it created, calling Dispose when the owning scope ends -- notably, Transient services are still tracked and disposed by their containing scope, not immediately after use, meaning many short-lived Transient disposables resolved repeatedly within one long-lived request scope are all held alive until that scope ends, which can cause unexpected memory retention in hot loops.
public class ReportExporter : IDisposable {
public void Dispose() => Console.WriteLine("Disposed");
}
builder.Services.AddTransient<ReportExporter>();
// Even though Transient, if resolved many times within one request scope,
// ALL instances are held and disposed together only when that request scope endsReal-world example
A memory profiling session reveals unexpectedly high memory retention within long request scopes traced to hundreds of Transient IDisposable service instances all being held alive until the scope's end rather than being freed immediately after each use.
Likely follow-ups
- Why doesn't the container dispose Transient services immediately after use?
- How would you work around this for a Transient disposable used many times in a loop?
Related topics