@@ -796,6 +796,53 @@ public void WindowServiceScopeIsDisposedOnDestroying()
796796 Assert . Throws < ObjectDisposedException > ( ( ) => scope . ServiceProvider . GetService < TestScopedService > ( ) ) ;
797797 }
798798
799+ [ Fact ]
800+ public void WindowServiceScopeHandlesNullScope ( )
801+ {
802+ // Test that destroying a window without a scope doesn't throw
803+ var mauiContext = new MockMauiContext ( ) ;
804+ var window = new TestWindow ( new ContentPage ( ) ) ;
805+ var handler = new WindowHandlerStub ( ) ;
806+ handler . SetMauiContext ( mauiContext ) ;
807+ window . Handler = handler ;
808+
809+ // This should not throw even though there's no scope to dispose
810+ ( ( IWindow ) window ) . Destroying ( ) ;
811+ }
812+
813+ [ Fact ]
814+ public void WindowServiceScopeWorksWithWindowCreationFlow ( )
815+ {
816+ // Test the full flow as it would happen in real usage
817+ var serviceCollection = new ServiceCollection ( ) ;
818+ serviceCollection . AddScoped < TestScopedService > ( ) ;
819+ var rootServiceProvider = serviceCollection . BuildServiceProvider ( ) ;
820+
821+ var appContext = new MauiContext ( rootServiceProvider ) ;
822+
823+ // Simulate the window creation flow
824+ var windowContext = appContext . MakeWindowScope ( new object ( ) , out var scope ) ;
825+
826+ // Verify we can get scoped services
827+ var service1 = windowContext . Services . GetRequiredService < TestScopedService > ( ) ;
828+ var service2 = windowContext . Services . GetRequiredService < TestScopedService > ( ) ;
829+
830+ // Should be the same instance since it's scoped
831+ Assert . Same ( service1 , service2 ) ;
832+
833+ // Create window and set up handler
834+ var window = new TestWindow ( new ContentPage ( ) ) ;
835+ var handler = new WindowHandlerStub ( ) ;
836+ handler . SetMauiContext ( windowContext ) ;
837+ window . Handler = handler ;
838+
839+ // Destroy the window
840+ ( ( IWindow ) window ) . Destroying ( ) ;
841+
842+ // Scope should be disposed
843+ Assert . Throws < ObjectDisposedException > ( ( ) => scope . ServiceProvider . GetService < TestScopedService > ( ) ) ;
844+ }
845+
799846 private class TestScopedService
800847 {
801848 public string TestProperty { get ; set ; } = "test" ;
0 commit comments