Phi*_*hil 9 .net c# dependency-injection maui
我正在尝试 .Net Maui、AppShell 和依赖注入。
我尝试使用构造函数调用页面,该构造函数将此页面的 ViewModel 作为参数。
构造函数如下所示:
public AuthenticationPage(AuthenticationViewModel viewModel)
{
InitializeComponent();
BindingContext = viewModel;
}
Run Code Online (Sandbox Code Playgroud)
在我的 MauiProgram.cs 中,我注册了页面和虚拟机
builder.Services.AddSingleton<AuthenticationViewModel>();
builder.Services.AddSingleton<AuthenticationPage>();
Run Code Online (Sandbox Code Playgroud)
我的 App.xaml.cs 如下所示:
public partial class App : Application
{
public App()
{
InitializeComponent();
MainPage = new AppShell();
}
}
Run Code Online (Sandbox Code Playgroud)
我的 AppShell.xaml 如下所示:
<Shell xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:pages="clr-namespace:DeepBlue.Pages"
xmlns:auth="clr-namespace:DeepBlue.Pages.Authentication"
x:Class="DeepBlue.AppShell">
<!-- Login and Registration Page -->
<ShellContent Route="login"
ContentTemplate="{DataTemplate auth:AuthenticationPage}">
</ShellContent>
<!-- Main Page -->
<FlyoutItem Route="main"
FlyoutDisplayOptions="AsMultipleItems">
<ShellContent Route="dashboard"
ContentTemplate="{DataTemplate pages:DashboardPage}"
Title="Home" />
</FlyoutItem>
</Shell>
Run Code Online (Sandbox Code Playgroud)
现在,当我执行我的项目时,出现以下错误:
System.MissingMethodException:“没有为类型‘DeepBlue.Pages.Authentication.AuthenticationPage’定义无参数构造函数。”
有人可以告诉我为什么依赖注入在这种情况下不起作用吗?
如果我不实现 AppShell,一切都会正常工作......我可以通过从我的 App.xaml.cs 注入将 AuthenticationPage 调用为 MainPage,如下所示:
public App(AuthenticationPage page)
{
InitializeComponent();
MainPage = page
}
Run Code Online (Sandbox Code Playgroud)
谢谢,菲尔
Mar*_*l W 11
2022 年 1 月的 Maui DevBlogs表明该功能已实现,但似乎由于某些问题而暂时删除了部分功能。目前有一个解决方法:在 MauiProgram.cs 的服务中添加需要 DI 的视图:
// Workaround for Shell/DataTemplates:
builder.Services.AddTransient<MainPage>();
builder.Services.AddTransient<AuthenticationPage>();
Run Code Online (Sandbox Code Playgroud)
希望 Shell 和 DataTemplates 的 DI 支持很快就能正确实现。
| 归档时间: |
|
| 查看次数: |
10110 次 |
| 最近记录: |