MAUI应用中如何在AppShell与App.xaml.cs实现依赖注入
解决MAUI中AppShell和App的依赖注入问题
你的错误根源清晰:DI容器仅注册了IAuthenticationService与AuthenticationService的映射关系,但你在App和AppShell的构造函数中直接依赖了具体类AuthenticationService,容器无法直接解析该具体类型。
正确的实现方式是始终依赖抽象接口而非具体实现类,修改步骤如下:
1. 修正AppShell.xaml.cs的构造函数
将构造函数参数改为接口类型IAuthenticationService:
public partial class AppShell : Shell { private readonly IAuthenticationService _authenticationService; public AppShell(IAuthenticationService authenticationService) { InitializeComponent(); _authenticationService = authenticationService; } }
2. 修正App.xaml.cs的构造函数
同样将参数改为接口类型,再传递给AppShell:
public partial class App : Application { public App(IAuthenticationService authenticationService) { InitializeComponent(); MainPage = new AppShell(authenticationService); } }
3. 确认MauiProgram.cs的注册保持不变
你当前的注册代码是正确的,无需修改:
builder.Services.AddSingleton<IAuthenticationService, AuthenticationService>();
修改完成后,DI容器就能正确解析IAuthenticationService的实例并注入到App和AppShell中,解决服务无法解析的错误。
内容的提问来源于stack exchange,提问作者adinas
相关产品推荐
相关产品推荐

