diff --git a/src/Controls/src/Core/Window/Window.cs b/src/Controls/src/Core/Window/Window.cs index 9c0015232793..429eccb62f12 100644 --- a/src/Controls/src/Core/Window/Window.cs +++ b/src/Controls/src/Core/Window/Window.cs @@ -545,12 +545,14 @@ void IWindow.Destroying() AlertManager.Unsubscribe(); Application?.RemoveWindow(this); - + var mauiContext = Handler?.MauiContext as MauiContext; Handler?.DisconnectHandler(); - // Dispose the window-scoped service scope + // On Android, preserve window scope to enable reuse when Activity is recreated +#if !ANDROID mauiContext?.DisposeWindowScope(); +#endif } void IWindow.Resumed() diff --git a/src/Controls/tests/DeviceTests/Elements/Window/WindowTests.Android.cs b/src/Controls/tests/DeviceTests/Elements/Window/WindowTests.Android.cs new file mode 100644 index 000000000000..1d46e8637726 --- /dev/null +++ b/src/Controls/tests/DeviceTests/Elements/Window/WindowTests.Android.cs @@ -0,0 +1,42 @@ +using System.Collections.Generic; +using System.Reflection; +using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Maui.Controls; +using Microsoft.Maui.DeviceTests.Stubs; +using Xunit; + +namespace Microsoft.Maui.DeviceTests +{ + public partial class WindowTests + { + [Fact] + public async Task WindowDestroyingPreservesWindowScopeOnAndroid() + { + // https://github.com/dotnet/maui/issues/33597 + SetupBuilder(); + + var window = new Window(new ContentPage()); + + await CreateHandlerAndAddToWindow(window, async handler => + { + await OnLoadedAsync(window.Page); + + var mauiContext = handler.MauiContext as MauiContext; + Assert.NotNull(mauiContext); + + var windowScopeField = typeof(MauiContext).GetField("_windowScope", BindingFlags.NonPublic | BindingFlags.Instance); + var setWindowScope = typeof(MauiContext).GetMethod("SetWindowScope", BindingFlags.NonPublic | BindingFlags.Instance); + + var newScope = mauiContext.Services.CreateScope(); + setWindowScope.Invoke(mauiContext, new[] { newScope }); + Assert.NotNull(windowScopeField.GetValue(mauiContext)); + + ((IWindow)window).Destroying(); + + Assert.NotNull(windowScopeField.GetValue(mauiContext)); + }); + } + + } +}