.NET MAUI添加OnboardingPage后Shell依赖注入导航异常求助
.NET MAUI 添加OnboardingPage后Shell导航异常:无法解析Shell服务及Shell.Current为空
之前.NET MAUI应用的页面导航完全正常,添加OnboardingPage后出现一系列Shell相关错误,无论怎么修复都无法解决,频繁出现Shell.Current为空的情况。最近持续触发的错误为:
System.InvalidOperationException: 'Unable to resolve service for type Microsoft.Maui.Controls.Shell while attempting to activate App.Core.Services.NavigationServices'
已尝试的排查步骤
- 检查路由配置:
- 确认OnboardingPage已在
AppShell.xaml.cs的Routing.RegisterRoute()中正确注册 - 反复核对路由名称,无拼写错误
- 其他页面(HomePage、HistoryPage、GoalPage)的导航路由在添加引导页前运行正常
- 确认OnboardingPage已在
- 尝试延迟Shell初始化:
- 在AppShell构造函数中使用
Task.Delay(100)确保Shell先加载完成 - 即使添加延迟,导航到引导页时
Shell.Current仍为空
- 在AppShell构造函数中使用
- 检查依赖注入(DI)配置:
- 已将AppShell在
MauiProgram.cs中注册为单例 - 导航服务
NavigationServices依赖于Shell,且添加引导页前DI配置正常 - 错误依然存在,说明DI容器未正确解析Shell
- 已将AppShell在
- 强制解析Shell:
- 在
CreateWindow()中尝试用_serviceProvider.GetRequiredService<AppShell>()获取AppShell实例 - 导航时仍出现空引用错误
- 在
当前困境
- 添加OnboardingPage前所有功能正常
- 现在因DI无法获取Shell导致导航完全失效
- 不清楚如何正确初始化Shell并确保其能被导航服务调用
相关代码
public partial class App : Application { private readonly IServiceProvider _serviceProvider; public App(IServiceProvider serviceProvider) { InitializeComponent(); _serviceProvider = serviceProvider; } protected override Window CreateWindow(IActivationState? activationState) { var shell = _serviceProvider.GetService<AppShell>(); if (shell == null) { throw new InvalidOperationException("AppShell could not be resolved from service provider."); } bool hasCompletedOnboarding = PreferencesServices.HasCompletedOnboarding(); // Navigate to the appropriate startup page inside the Shell Task.Run(async () => { await Task.Delay(100); // Small delay to ensure Shell initializes await shell.GoToAsync(hasCompletedOnboarding ? "//home" : "//onboarding"); }); return new Window(shell); } } public AppShell() { InitializeComponent(); Routing.RegisterRoute("home", typeof(HomePage)); Routing.RegisterRoute("onboarding", typeof(OnboardingPage)); Routing.RegisterRoute("history", typeof(HistoryPage)); Routing.RegisterRoute("goal", typeof(GoalPage)); Dispatcher.Dispatch(async () => await InitializeShellAsync()); } private async Task InitializeShellAsync() { await Task.Delay(100); bool hasCompletedOnboarding = PreferencesServices.HasCompletedOnboarding(); if (!hasCompletedOnboarding) { Console.WriteLine("[DEBUG] Navigating to onboarding..."); await Shell.Current.GoToAsync("//onboarding"); } }
内容的提问来源于stack exchange,提问作者Renia
相关产品推荐
相关产品推荐

