|
13 | 13 | using OpenClawTray.Services; |
14 | 14 | using OpenClawTray.Windows; |
15 | 15 | using OpenClaw.Connection; |
| 16 | +using Microsoft.Extensions.DependencyInjection; |
| 17 | +using OpenClawTray.Presentation; |
| 18 | +using OpenClawTray.Presentation.Adapters; |
16 | 19 | using System; |
17 | 20 | using System.Collections.Frozen; |
18 | 21 | using System.Collections.Generic; |
@@ -49,6 +52,29 @@ public partial class App : Application, OpenClawTray.Services.IAppCommands |
49 | 52 | private GatewayConnectionManager? _connectionManager; |
50 | 53 | private GatewayRegistry? _gatewayRegistry; |
51 | 54 | private OpenClawTray.Chat.OpenClawChatCoordinator? _chatCoordinator; |
| 55 | + |
| 56 | + /// <summary> |
| 57 | + /// Root DI composition root, built once during startup and disposed during |
| 58 | + /// shutdown. The container only owns the presentation infrastructure it creates |
| 59 | + /// (navigation scope manager + any open page-view-model scope); App-owned |
| 60 | + /// services are registered as pre-built instances, so the container never |
| 61 | + /// disposes them and there is no double-dispose. |
| 62 | + /// </summary> |
| 63 | + private ServiceProvider? _services; |
| 64 | + |
| 65 | + /// <summary> |
| 66 | + /// Page type → view-model type map used by the navigation activation hook. |
| 67 | + /// Currently empty: no page resolves a view model from DI yet, so the activation |
| 68 | + /// hook is a runtime no-op. Entries are added here as pages adopt view models. |
| 69 | + /// </summary> |
| 70 | + private static readonly IReadOnlyDictionary<Type, Type> PageViewModelMap = |
| 71 | + new Dictionary<Type, Type>(); |
| 72 | + |
| 73 | + /// <summary>The root service provider, or null before startup / after shutdown.</summary> |
| 74 | + internal IServiceProvider? Services => _services; |
| 75 | + |
| 76 | + /// <summary>Resolves the page activator used by <c>HubWindow</c>'s navigation hook.</summary> |
| 77 | + internal IPageActivator? PageActivator => _services?.GetService<IPageActivator>(); |
52 | 78 | /// <summary> |
53 | 79 | /// Cached reference to the most recently constructed local-setup engine. Used by |
54 | 80 | /// <see cref="OnPairingStatusChanged"/> to suppress the "copy pairing command" toast |
@@ -403,6 +429,70 @@ private void OnProcessExit(object? sender, EventArgs e) |
403 | 429 | return null; |
404 | 430 | } |
405 | 431 |
|
| 432 | + /// <summary> |
| 433 | + /// Builds the root DI composition root exactly once. Registers the WinUI-free |
| 434 | + /// core (dispatcher/app-commands/settings as pre-built instances, the navigation |
| 435 | + /// scope manager, and transient page view models) plus the WinUI-bound adapters |
| 436 | + /// (navigation service + page activator). Built with scope and build-time |
| 437 | + /// validation so wiring errors surface at startup rather than first use. No |
| 438 | + /// registered service starts work in its constructor. |
| 439 | + /// </summary> |
| 440 | + private void InitializeServiceProvider() |
| 441 | + { |
| 442 | + if (_services is not null) |
| 443 | + { |
| 444 | + return; |
| 445 | + } |
| 446 | + |
| 447 | + if (_dispatcherQueue is null || _settings is null) |
| 448 | + { |
| 449 | + Logger.Warn("Skipping service provider init: dispatcher or settings not ready."); |
| 450 | + return; |
| 451 | + } |
| 452 | + |
| 453 | + var dispatcher = new WinUIDispatcher(_dispatcherQueue); |
| 454 | + var context = new AppServiceContext(dispatcher, this, _settings); |
| 455 | + |
| 456 | + var services = new ServiceCollection(); |
| 457 | + services.AddOpenClawTrayCore(context); |
| 458 | + |
| 459 | + // WinUI-bound registrations are added here (not in the pure core) so the core |
| 460 | + // stays testable in a pure net10 project. |
| 461 | + services.AddSingleton<INavigationService>(new AppNavigationService( |
| 462 | + dispatcher, |
| 463 | + navigate: tag => ((IAppCommands)this).Navigate(tag), |
| 464 | + canGoBack: () => _hubWindow is { IsClosed: false } hub && hub.CanGoBack, |
| 465 | + goBack: () => |
| 466 | + { |
| 467 | + if (_hubWindow is { IsClosed: false } hub) |
| 468 | + { |
| 469 | + hub.NavigateBack(); |
| 470 | + } |
| 471 | + })); |
| 472 | + services.AddSingleton<IPageActivator>(sp => new FramePageActivator( |
| 473 | + sp.GetRequiredService<NavigationScopeManager>(), |
| 474 | + PageViewModelMap)); |
| 475 | + |
| 476 | + try |
| 477 | + { |
| 478 | + _services = services.BuildServiceProvider(new ServiceProviderOptions |
| 479 | + { |
| 480 | + ValidateScopes = true, |
| 481 | + ValidateOnBuild = true, |
| 482 | + }); |
| 483 | + Logger.Info("Service provider initialized."); |
| 484 | + } |
| 485 | + catch (Exception ex) |
| 486 | + { |
| 487 | + // Additive plumbing must never take the tray down. A build/validation |
| 488 | + // failure is logged and leaves _services null, so the navigation |
| 489 | + // activation hook stays a no-op. Wiring regressions are caught by tests |
| 490 | + // (AppServiceRegistrationTests builds with ValidateOnBuild). |
| 491 | + _services = null; |
| 492 | + Logger.Error($"Service provider initialization failed: {ex}"); |
| 493 | + } |
| 494 | + } |
| 495 | + |
406 | 496 | protected override void OnLaunched(LaunchActivatedEventArgs args) => |
407 | 497 | AsyncEventHandlerGuard.Run( |
408 | 498 | () => OnLaunchedAsync(args), |
@@ -607,6 +697,11 @@ _dispatcherQueue is null |
607 | 697 | InitializeTrayIcon(); |
608 | 698 | ShowSurfaceImprovementsTipIfNeeded(); |
609 | 699 |
|
| 700 | + // Build the DI composition root AFTER the tray is up, so additive plumbing |
| 701 | + // can never delay or preempt tray initialization. It only needs the |
| 702 | + // dispatcher + settings (created above) and failures are non-fatal. |
| 703 | + InitializeServiceProvider(); |
| 704 | + |
610 | 705 | // Initialize connection manager before setup flow. |
611 | 706 | _gatewayRegistry = new GatewayRegistry(SettingsManager.SettingsDirectoryPath, logger: new AppLogger()); |
612 | 707 | _gatewayRegistry.Load(); |
@@ -3303,6 +3398,17 @@ internal void ShowHub(string? navigateTo = null, bool activate = true) |
3303 | 3398 | { |
3304 | 3399 | _hubWindow.SettingsSaved -= OnSettingsSaved; |
3305 | 3400 | _hubWindow = null; |
| 3401 | + |
| 3402 | + // Deactivate + dispose the current navigation scope so a page view model |
| 3403 | + // (once pages are mapped) does not outlive the window it belonged to. |
| 3404 | + try |
| 3405 | + { |
| 3406 | + PageActivator?.Reset(); |
| 3407 | + } |
| 3408 | + catch (Exception ex) |
| 3409 | + { |
| 3410 | + Logger.Warn($"[App] Navigation scope reset on hub close failed: {ex.Message}"); |
| 3411 | + } |
3306 | 3412 | }; |
3307 | 3413 |
|
3308 | 3414 | _hubWindow.BindToAppState(); |
@@ -4525,6 +4631,22 @@ await SafeShutdownStepAsync("standalone voice service", async () => |
4525 | 4631 | SafeShutdownStep("keep alive window", () => CloseWindow(_keepAliveWindow)); |
4526 | 4632 | _keepAliveWindow = null; |
4527 | 4633 |
|
| 4634 | + // Dispose the DI composition root. The container only owns the presentation |
| 4635 | + // infrastructure it created (navigation scope manager + any open page-view-model |
| 4636 | + // scope). App-owned services were registered as pre-built instances, so this |
| 4637 | + // does not re-dispose them (no double-dispose). Null the field BEFORE awaiting |
| 4638 | + // disposal so a queued Frame.Navigated callback during shutdown cannot resolve |
| 4639 | + // the page activator against a disposing/disposed provider. |
| 4640 | + var services = _services; |
| 4641 | + _services = null; |
| 4642 | + if (services is not null) |
| 4643 | + { |
| 4644 | + await SafeShutdownStepAsync("service provider", async () => |
| 4645 | + { |
| 4646 | + await services.DisposeAsync(); |
| 4647 | + }); |
| 4648 | + } |
| 4649 | + |
4528 | 4650 | // Dispose tray and mutex |
4529 | 4651 | SafeShutdownStep("tray icon", () => |
4530 | 4652 | { |
|
0 commit comments