Skip to content

6.10 — Disposal: Who Disposes What

← Roadmap · Section: 6. Dependency Injection Prev: 6.9 Injection styles · Next: 6.11 Third-party containers

Markers: ⭐ ⚠️ · Confidence: 🔴 · Last reviewed: —


TL;DR

The container disposes what it created. That single rule answers almost every question here.

  • Services the container constructed are disposed when their scope ends — scoped and transient at end of request, singletons at shutdown.
  • An instance you built yourself and passed to AddSingleton(instance) is not disposed. You own it.
  • Never dispose an injected service manually. The container will dispose it again, and the next request gets an ObjectDisposedException.

Definitions

Term What it is What it means
IDisposable an interface Has Dispose(). Releases unmanaged resources. See 1.21.
IAsyncDisposable an interface Has DisposeAsync(). For cleanup that needs to await.
Container-created a service the container built Registered by type or factory. The container owns its disposal.
Container-provided an instance you supplied Passed to AddSingleton(instance). You own its disposal.
Disposal tracking a container behaviour The scope keeps a list of disposables it created, and disposes them in reverse order.
ObjectDisposedException an exception Using a service after it was disposed. The symptom of double disposal.
CreateAsyncScope() a method A scope that can dispose IAsyncDisposable services correctly.
Transient disposable a leak risk A transient implementing IDisposable — held by the scope until it ends, not when you finish.

The concept

The rule

The container disposes what it created. It does not dispose what you handed it.

Everything follows from that.

// Container CREATES it → container DISPOSES it
builder.Services.AddScoped<IFileStore, FileStore>();

// Container CREATES it (via your factory) → container DISPOSES it
builder.Services.AddSingleton<IFileStore>(sp => new FileStore("/data"));

// YOU created it → YOU dispose it. Container will not.
builder.Services.AddSingleton<IFileStore>(new FileStore("/data"));

Those last two look almost identical and behave differently. The factory version hands the container a recipe, so the container owns the result. The instance version hands over a finished object, and the container assumes you are managing it.

A picture: a restaurant washing the plates it owns. Bring your own plate and they will serve food on it, but they will not put it through the dishwasher — they assume you are taking it home.

When disposal happens

Lifetime Disposed when
Transient The scope that created it ends
Scoped That scope ends — end of the HTTP request
Singleton The application shuts down
Instance you supplied Never — by the container

Disposal happens in reverse creation order, so a service is disposed before anything it depended on. Same logic as nested using blocks.


How it works

The simple version — you do nothing

For the overwhelming majority of services, disposal is automatic and invisible:

builder.Services.AddDbContext<AppDbContext>(...);      // scoped, IAsyncDisposable
public class OrdersController(AppDbContext db) : ControllerBase
{
    public async Task<IActionResult> Get(Guid id, CancellationToken ct)
    {
        var order = await db.Orders.FindAsync([id], ct);
        return Ok(order);
    }
    // No using, no Dispose. The request scope handles it.
}

⚠️ Never dispose an injected service

This is the trap:

// ✗ WRONG
public class OrderService(AppDbContext db) : IOrderService
{
    public async Task ProcessAsync(CancellationToken ct)
    {
        using (db)                             // ⚠️ don't
        {
            await db.SaveChangesAsync(ct);
        }
    }
}

You did not create it, so it is not yours to dispose. Two things go wrong:

The rest of the request breaks. Other services sharing that scoped DbContext now get ObjectDisposedException.

The container disposes it again at end of scope. Dispose should be idempotent, so that usually does not throw — but you have introduced a real bug for a cleanup you never needed.

The rule: if it arrived through injection, you do not dispose it.

How it actually works — transient disposables ⚠️

The genuinely surprising one.

A transient service implementing IDisposable is tracked by the scope that created it, and disposed when that scope ends — not when you finish using it:

builder.Services.AddTransient<IFileHandle, FileHandle>();      // IDisposable
public class BatchProcessor(IServiceProvider provider)
{
    public async Task ProcessAsync(IEnumerable<string> paths, CancellationToken ct)
    {
        foreach (var path in paths)
        {
            var handle = provider.GetRequiredService<IFileHandle>();
            await handle.WriteAsync(path, ct);
            // ⚠️ NOT disposed here — held until the scope ends
        }
        // 10,000 files → 10,000 open file handles
    }
}

The container held every one, so the operating system handles stay open until the request completes. On a long-running scope — a background service loop — this is a real leak (3.5).

The fix is a scope per unit of work, so disposal happens when you expect:

foreach (var path in paths)
{
    using var scope = scopeFactory.CreateScope();
    var handle = scope.ServiceProvider.GetRequiredService<IFileHandle>();
    await handle.WriteAsync(path, ct);
}   // disposed here, every iteration

⚠️ The broader guidance: avoid registering disposable services as transient. If it holds a resource, scoped is usually more appropriate, because the disposal point is then clear.

Async disposal

DbContext implements IAsyncDisposable. Disposing it synchronously can block a thread or throw:

// ✗ May not dispose async services correctly
using var scope = scopeFactory.CreateScope();

// ✓ Handles IAsyncDisposable properly
await using var scope = scopeFactory.CreateAsyncScope();

CreateAsyncScope was added specifically because CreateScope could not dispose those services correctly. Prefer it whenever the scope might hold something async-disposable, which in practice means whenever a DbContext is involved. See 6.5.

The deeper detail — HttpClient is the exception

The one service you must not dispose, and which the container deliberately does not either:

public class ApiClient(HttpClient http)         // from IHttpClientFactory
{
    public void Dispose() => http.Dispose();    // ✗ NEVER
}

IHttpClientFactory manages the underlying HttpClientHandler pool, rotating handlers on a schedule so DNS changes are picked up. Disposing the client defeats that mechanism entirely.

An HttpClient from the factory is safe to let go of — it is a lightweight wrapper. The handler underneath is pooled and reused. See 19.10.

The captive disposal problem

A singleton holding a scoped disposable is a captive dependency (6.4) — and it is also a disposal problem, because the scoped service is never disposed until shutdown:

// ✗ The DbContext is never disposed until the app stops
public class CacheWarmer(AppDbContext db) { }

Beyond the thread-safety issue, the database connection and change tracker are held for the application's lifetime.


Code

Getting it right in the cases that matter:

// ── 1. Normal service — do nothing. The container handles it. ──
public class OrderService(AppDbContext db, IEmailSender email) : IOrderService
{
    public async Task CompleteAsync(Guid id, CancellationToken ct)
    {
        var order = await db.Orders.FindAsync([id], ct);
        order!.Complete();
        await db.SaveChangesAsync(ct);
        await email.SendAsync(order.CustomerEmail, "Done", ct);
    }
    // No IDisposable. Nothing to clean up. Nothing was created here.
}
// ── 2. A service that creates something itself — it owns that ──
public class ReportService(IServiceScopeFactory scopeFactory) : IReportService
{
    public async Task<byte[]> GenerateAsync(CancellationToken ct)
    {
        // WE created this stream, so WE dispose it
        await using var buffer = new MemoryStream();

        // The scope we created is also ours to dispose
        await using var scope = scopeFactory.CreateAsyncScope();
        var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();

        var orders = await db.Orders.AsNoTracking().ToListAsync(ct);
        await WriteReportAsync(buffer, orders, ct);

        return buffer.ToArray();
    }   // buffer and scope disposed. The DbContext goes with the scope.
}
// ── 3. A disposable singleton — the container disposes at shutdown ──
public sealed class ConnectionPool(IOptions<PoolOptions> options) : IDisposable
{
    private readonly SemaphoreSlim _limit = new(options.Value.MaxConnections);

    public void Dispose() => _limit.Dispose();
}

builder.Services.AddSingleton<ConnectionPool>();     // container built it → disposes it
// ── 4. An instance you built — YOU own it ──
var pool = new ConnectionPool(Options.Create(new PoolOptions { MaxConnections = 10 }));
builder.Services.AddSingleton(pool);

// ⚠️ The container will NOT dispose this. If it holds a real resource,
// you must dispose it yourself on shutdown:
app.Lifetime.ApplicationStopped.Register(() => pool.Dispose());

That fourth case is the one worth remembering, because it looks identical to the third at the call site.


Interview questions

Q: Who is responsible for disposing services in ASP.NET Core?

The container disposes what it created. If you register by type or with a factory, the container constructs the instance and disposes it when its scope ends — scoped and transient services at the end of the request, singletons at application shutdown. The exception is an instance you construct yourself and pass to AddSingleton, because the container did not create it and assumes you are managing its lifetime. So it will not dispose it, and if it holds a real resource you have to do that yourself, typically on the application-stopped lifetime event.

Q: Should you ever call Dispose on an injected service?

No. If it arrived through injection you did not create it, so it is not yours to dispose. Disposing a scoped DbContext inside one service breaks every other service in that request that shares it — they get ObjectDisposedException — and the container will dispose it again at the end of the scope. You only dispose what you created yourself, like a MemoryStream you opened or a scope you called CreateScope on.

Q: What is the problem with transient disposable services?

They are not disposed when you finish with them — they are tracked by the scope that created them and disposed when that scope ends. So resolving a transient disposable in a loop means every instance is held until the request or scope completes, which for something holding a file handle or a connection is a genuine leak. The fix is a scope per unit of work so disposal happens at a predictable point, and the broader guidance is to avoid registering disposable services as transient at all — if it holds a resource, scoped usually makes the disposal point clearer.

Q: Why must you not dispose an HttpClient from IHttpClientFactory?

Because the factory manages the underlying HttpClientHandler pool, rotating handlers periodically so DNS changes are picked up while reusing connections. The HttpClient you receive is a lightweight wrapper over a pooled handler, so disposing it defeats the pooling and undermines the whole reason for using the factory. You just let it go out of scope.


Traps ⚠️

  • Disposing an injected service breaks the rest of the request for anything sharing it.
  • AddSingleton(instance) is not disposed by the container. You own it.
  • Transient disposables are held until the scope ends, not when you finish with them.
  • CreateScope cannot dispose IAsyncDisposable services properly. Use CreateAsyncScope.
  • Never dispose an HttpClient from IHttpClientFactory.
  • A scoped disposable captured by a singleton is never disposed until shutdown.
  • Dispose must be safe to call twice, because double disposal does happen.
  • A long-lived scope accumulates every disposable it created, including transients.


Sources