microsoft/aspire · error · ObjectDisposedException

Cannot allocate temporary files after the service has been…

Error message

Cannot allocate temporary files after the service has been disposed.

What it means

FileSystemService tracks allocated temporary files so it can clean them up on disposal. TrackItem throws ObjectDisposedException when a temporary file allocation is attempted after the FileSystemService (an IHostedService) has been disposed, i.e. during or after AppHost shutdown. Allocating temp files at that point would leak or race with disposal.

Solutions

  1. Move temp-file allocation earlier in the lifecycle (before shutdown), or cancel/await background work during host shutdown
  2. Register IHostApplicationLifetime.ApplicationStopping to stop work that allocates temp files
  3. If needed during shutdown, create temp dirs via Directory.CreateTempSubdirectory() instead of FileSystemService

Example fix

// before (background work keeps running after host disposal)
_ = Task.Run(async () => { var dir = fileSystemService.TempDirectory; ... });
// after
using var cts = new CancellationTokenSource();
lifetime.ApplicationStopping.Register(() => cts.Cancel());
_ = Task.Run(async () => { var dir = fileSystemService.TempDirectory; ... }, cts.Token);
Defensive patterns

Strategy: try-catch

Validate before calling

if (((IHostedService)fileSystemService) is { } && hostIsShuttingDown) // or track lifetime state
    return Directory.CreateTempSubdirectory();

Type guard

bool CanAllocateTempFiles(IFileSystemService fs, IHostApplicationLifetime lifetime) => !lifetime.ApplicationStopping.IsCancellationRequested;

Try / catch

try { var dir = fileSystemService.TempDirectory; }
catch (ObjectDisposedException ex) when (ex.ObjectName == nameof(FileSystemService))
{ dir = Directory.CreateTempSubdirectory(); } // fallback allocation during shutdown

Prevention

When it happens

Trigger: Calling IFileSystemService.TempDirectory/GetTempFile (or anything allocating temp items) from code that runs after AppHost shutdown begins — e.g. background tasks, event handlers firing during stop, or callbacks that continue after the host is disposed.

Common situations: Fire-and-forget tasks that outlive the host, resource-stopped event handlers doing cleanup that writes temp files, or tests that dispose the host and then exercise an extension that allocates temp files.

Understand the failure class

Background: UnsupportedOperationException and "is not supported" errors: when a library deliberately refuses a call — this error's family across 30 libraries.

Related errors


AI-assisted analysis of microsoft/aspire@25830f84bd (2026-09-16). Data as JSON: /api/errors/861431beee6c8847. Report an issue: GitHub.

Appendix: source

Thrown at src/Aspire.Hosting/Utils/FileSystemService.cs:71

    /// <summary>
    /// Gets the logger for this service, if set.
    /// </summary>
    internal ILogger? Logger => _logger;

    private bool _disposed;
    private readonly object _disposeLock = new();

    /// <summary>
    /// Tracks a temporary item for cleanup on service disposal.
    /// </summary>
    internal void TrackItem(string path, IDisposable item)
    {
        lock (_disposeLock)
        {
            if (_disposed)
            {
                throw new ObjectDisposedException(nameof(FileSystemService), "Cannot allocate temporary files after the service has been disposed.");
            }

            _allocatedItems.TryAdd(path, item);
        }
    }

    /// <summary>
    /// Removes a temporary item from tracking.
    /// </summary>
    internal void UntrackItem(string path)
    {
        _allocatedItems.TryRemove(path, out _);
    }

    /// <summary>
    /// Cleans up any remaining temporary files and directories.
    /// </summary>
    public void Dispose()

View on GitHub (pinned to 25830f84bd)