Skip to content

Commit 4b18b04

Browse files
CopilotPureWeen
andcommitted
Add comprehensive tests for service scope disposal
Co-authored-by: PureWeen <[email protected]>
1 parent 94ee9ac commit 4b18b04

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

src/Controls/tests/Core.UnitTests/WindowsTests.cs

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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

Comments
 (0)