{"record":{"id":"861431beee6c8847","repo":"microsoft/aspire","slug":"cannot-allocate-temporary-files-after-the-service-has-been","errorCode":null,"errorMessage":"Cannot allocate temporary files after the service has been disposed.","messagePattern":"Cannot allocate temporary files after the service has been disposed\\.","errorType":"exception","errorClass":"ObjectDisposedException","httpStatus":null,"severity":"error","filePath":"src/Aspire.Hosting/Utils/FileSystemService.cs","lineNumber":71,"sourceCode":"\n    /// <summary>\n    /// Gets the logger for this service, if set.\n    /// </summary>\n    internal ILogger? Logger => _logger;\n\n    private bool _disposed;\n    private readonly object _disposeLock = new();\n\n    /// <summary>\n    /// Tracks a temporary item for cleanup on service disposal.\n    /// </summary>\n    internal void TrackItem(string path, IDisposable item)\n    {\n        lock (_disposeLock)\n        {\n            if (_disposed)\n            {\n                throw new ObjectDisposedException(nameof(FileSystemService), \"Cannot allocate temporary files after the service has been disposed.\");\n            }\n\n            _allocatedItems.TryAdd(path, item);\n        }\n    }\n\n    /// <summary>\n    /// Removes a temporary item from tracking.\n    /// </summary>\n    internal void UntrackItem(string path)\n    {\n        _allocatedItems.TryRemove(path, out _);\n    }\n\n    /// <summary>\n    /// Cleans up any remaining temporary files and directories.\n    /// </summary>\n    public void Dispose()","sourceCodeStart":53,"sourceCodeEnd":89,"githubUrl":"https://github.com/microsoft/aspire/blob/25830f84bd145686607ad00c057b3f84e2e51d43/src/Aspire.Hosting/Utils/FileSystemService.cs#L53-L89","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Move temp-file allocation earlier in the lifecycle (before shutdown), or cancel/await background work during host shutdown","Register IHostApplicationLifetime.ApplicationStopping to stop work that allocates temp files","If needed during shutdown, create temp dirs via Directory.CreateTempSubdirectory() instead of FileSystemService"],"exampleFix":"// before (background work keeps running after host disposal)\n_ = Task.Run(async () => { var dir = fileSystemService.TempDirectory; ... });\n// after\nusing var cts = new CancellationTokenSource();\nlifetime.ApplicationStopping.Register(() => cts.Cancel());\n_ = Task.Run(async () => { var dir = fileSystemService.TempDirectory; ... }, cts.Token);","handlingStrategy":"try-catch","validationCode":"if (((IHostedService)fileSystemService) is { } && hostIsShuttingDown) // or track lifetime state\n    return Directory.CreateTempSubdirectory();","typeGuard":"bool CanAllocateTempFiles(IFileSystemService fs, IHostApplicationLifetime lifetime) => !lifetime.ApplicationStopping.IsCancellationRequested;","tryCatchPattern":"try { var dir = fileSystemService.TempDirectory; }\ncatch (ObjectDisposedException ex) when (ex.ObjectName == nameof(FileSystemService))\n{ dir = Directory.CreateTempSubdirectory(); } // fallback allocation during shutdown","preventionTips":["Cancel background work on ApplicationStopping before it allocates temp files","Avoid temp-file allocation in resource-stopped/shutdown event handlers","Use Directory.CreateTempSubdirectory() as a fallback late in the lifecycle"],"tags":["aspire","lifetime","temp-files","disposal"],"backgroundTag":"unsupported-operation","analyzedSha":"25830f84bd145686607ad00c057b3f84e2e51d43","analyzedAt":"2026-09-16T11:10:06.193Z","contentChangedAt":"2026-09-16T11:10:06.193Z","schemaVersion":2},"datasetVersion":"2026-09-21T09:17:21.228Z"}