Skip to content

[VS2026] InvalidOperationException on solution close: "Failed to get service MenuService" after package disposal #144

Open

Description

@xperiandri

Current behavior

When Visual Studio is closing a solution, Uno Studio throws:

System.InvalidOperationException: Failed to get service MenuService

This is not a “MenuService was never implemented” failure. Cleanup runs after the VS package and its DI container are already torn down, then treats a missing service as fatal.

Exception

  • Type: System.InvalidOperationException
  • Message: Failed to get service MenuService
  • Assembly: Studio.Extensions.dll
  • Process: devenv.exe
  • Thread ID: 111696

Call stack (from paused debugger)

[1]  Studio.Extensions.dll!UnoSolutionTemplate.UnoServiceProvider.GetServiceAsync<Studio.Extensions.UI.MenuService>
     // throw site; generic result `t` is null
[2]  Studio.Extensions.dll!UnoSolutionTemplate.UnoPlatformPackage.CleanupEnvironmentAsync
[3]  [Resuming Async Method]
[4]  mscorlib.dll!System.Runtime.CompilerServices.AsyncMethodBuilderCore.MoveNextRunner.InvokeMoveNext
[5]  mscorlib.dll!System.Threading.ExecutionContext.RunInternal
[6]  mscorlib.dll!System.Threading.ExecutionContext.Run
[7]  mscorlib.dll!System.Runtime.CompilerServices.AsyncMethodBuilderCore.MoveNextRunner.Run
[8]  mscorlib.dll!System.Runtime.CompilerServices.AsyncMethodBuilderCore.OutputAsyncCausalityEvents.AnonymousMethod__0
[9]  mscorlib.dll!System.Runtime.CompilerServices.AsyncMethodBuilderCore.ContinuationWrapper.Invoke
[10] mscorlib.dll!System.Runtime.CompilerServices.TaskAwaiter.OutputWaitEtwEvents.AnonymousMethod__0
[11] mscorlib.dll!System.Runtime.CompilerServices.AsyncMethodBuilderCore.ContinuationWrapper.Invoke
[12] mscorlib.dll!System.Threading.Tasks.AwaitTaskContinuation.ExecuteWorkItemHelper
[13] mscorlib.dll!System.Threading.Tasks.AwaitTaskContinuation.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem
[14] mscorlib.dll!System.Threading.ThreadPoolWorkQueue.Dispatch
[15] mscorlib.dll!System.Threading._ThreadPoolWaitCallback.PerformWaitCallback
[16] [Async Call Stack]
[17] [Async] Studio.Extensions.dll!UnoSolutionTemplate.UnoPlatformPackage.OnSolutionClosing.AnonymousMethod__0
[18] [Async] mscorlib.dll!System.Threading.Tasks.Task.Run

Logical sequence:

  1. UnoPlatformPackage.OnSolutionClosing
  2. Task.Run(...) (thread-pool continuation, not VS JoinableTaskFactory)
  3. CleanupEnvironmentAsync
  4. UnoServiceProvider.GetServiceAsync<MenuService>()
  5. service not found (t == null) → InvalidOperationException

Expected behavior

Solution close / package unload should not throw. Cleanup must tolerate already-zombied/disposed package state and missing solution-scoped services.

Environment

  • IDE: Microsoft Visual Studio Enterprise 2026 (18.10.0-insiders)
  • Solution being closed was a non-Uno workspace (VisualFSharp.slnx / dotnet/fsharp)
  • Captured while debugging devenv.exe

Debugger state at throw site

GetServiceAsync<MenuService> locals:

  • this: {UnoSolutionTemplate.UnoServiceProvider}
  • t: null (Studio.Extensions.UI.MenuService)

Same UnoServiceProvider instance (package._services == this):

Field / expression Value
_parent null
_children null
_registrations null
_ct.IsCancellationRequested true
_ct.Token throws ObjectDisposedException
_innerAsync / _innerSync UnoPlatformPackage
_currentSolutionScope null

Package (UnoPlatformPackage / AsyncPackage):

Field / expression Value
Package.Zombied true
AsyncPackage.DisposalToken.IsCancellationRequested true
ApplicationRegistryRoot null
UserRegistryRoot null
_inflightSolutionPath null
_currentSolutionScope null

Interpretation:

  • VS already zombied/unloaded the package.
  • Provider CTS is cancelled and disposed.
  • DI registration table is cleared (_registrations == null).
  • Solution scope is already gone, so MenuService cannot be resolved even if it was registered as a solution-scoped service.

Root cause

Shutdown-order / lifetime race:

  1. OnSolutionClosing queues cleanup with Task.Run.
  2. VS continues package dispose (Zombied = true, DisposalToken cancelled).
  3. Provider tears down: cancel+dispose CTS, drop _registrations.
  4. Thread-pool continuation still runs CleanupEnvironmentAsync.
  5. Cleanup requires MenuService via GetServiceAsync, which throws on miss instead of returning null / becoming a no-op.

GetServiceAsync is the immediate throw. The real bug is cleanup assuming live services after dispose.

How to fix

Minimum (stop the crash):

  1. Do not resolve required services during shutdown. In CleanupEnvironmentAsync, return immediately if:
    • Zombied
    • DisposalToken.IsCancellationRequested
    • provider _registrations is null
    • provider CTS is cancelled/disposed
  2. Use try-get, not throw-get. Add TryGetServiceAsync<T>() (or catch this specific miss) and skip menu cleanup when MenuService is already gone. Closing a solution after the service is disposed is already a no-op.
  3. Do not Task.Run cleanup. Schedule with JoinableTaskFactory and pass DisposalToken so the continuation is cancelled when the package dies, instead of running on a raw thread-pool after teardown.

Better (correct lifetime):

  1. Cache MenuService at init / solution-open, then dispose/reset that field in close. Do not look it up again during close.
  2. If MenuService is solution-scoped, clean it up before disposing _currentSolutionScope / _registrations, not after.
  3. Make GetServiceAsync throw only for unexpected misses during normal operation; shutdown should be best-effort and never fatal.

Sketch of the defensive path:

private async Task CleanupEnvironmentAsync()
{
    if (Zombied || DisposalToken.IsCancellationRequested)
        return;

    var menu = await _services.TryGetServiceAsync<MenuService>(DisposalToken).ConfigureAwait(false);
    if (menu is null)
        return;

    await menu.CleanupAsync(DisposalToken).ConfigureAwait(false);
}

And for scheduling:

// instead of Task.Run
JoinableTaskFactory.RunAsync(async () =>
{
    await CleanupEnvironmentAsync().ConfigureAwait(false);
}).Task.Forget(); // still honor DisposalToken inside CleanupEnvironmentAsync

Repro notes

Captured in a paused debug session during solution-close cleanup. Repro is intermittent because it depends on the race between Task.Run continuation and package dispose.

Happy to add a dump / extra locals if useful.

Activity

  1. changed the title [-][VS2026] InvalidOperationException on solution close: "Failed to get service MenuService" after package disposal[/-] [+][VS2026] `InvalidOperationException` on solution close: "Failed to get service MenuService" after package disposal[/+] on Aug 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions