我試圖了解如何在 .NET MAUI 應用程式中實作依賴注入。
我有一個服務類 - 及其介面 - 處理我的 REST 呼叫,如下所示:
public class MyRestApiService : IMyRestApiService
{
public async Task<string> Get()
{
// Do someting
}
}
然后我把它放在我的 DI 容器中MauiProgram.cs:
builder.Service.AddTransient<IMyRestApiService, MyRestApiService>();
我還有一個視圖模型,我將用于我的MainPage.xaml. 問題是,如果我對我的服務進行建構式注入,XAML 似乎不喜歡它。
MainPageViewModel看起來像這樣:
public class MainPageViewModel : BaseViewModel
{
IMyRestApiService _apiService;
public MainPageViewModel(IMyRestApiService apiService)
{
_apiService = apiService;
}
}
當我嘗試定義MainPageViewModel如下的視圖模型時MainPage.xaml,出現錯誤:
<ContentPage.BindingContext>
<vm:MainPageViewModel />
</ContentPage.BindingContext>
錯誤內容如下:
型別 MainPageViewModel 不能用作物件元素,因為它不是公共的或未定義公共無引數建構式或型別轉換器。
如何將我的服務注入到我的視圖模型中?
uj5u.com熱心網友回復:
您將希望基本上從第一頁解決所有問題,以使所有內容都到位并進行依賴注入。
看看這個例子:https ://github.com/jfversluis/MauiDependencyInjectionSample
您將需要注冊您的服務、視圖模型和視圖。在您的情況下,在您的MauiProgram.cs添加中:
// Change scopes as needed, this seems to make sense
builder.Service.AddTransient<MainPage>();
builder.Service.AddTransient<MainPageViewModel>();
builder.Service.AddSingleton<IMyRestApiService, MyRestApiService>();
然后在你App.xaml.cs也開始注入你的(主)頁面:
public partial class App : Application
{
public App(MainPage page)
{
InitializeComponent();
MainPage = page;
}
}
現在在你MainPage.xaml.cs添加一個這樣的建構式:
public LoginPage(MainPageViewModel viewModel)
{
InitializeComponent();
BindingContext = viewModel;
}
從那里一切都應該效仿并連接起來。你想做什么
<ContentPage.BindingContext>
<vm:MainPageViewModel />
</ContentPage.BindingContext>
基本上是BindingContext通過屬性設定的。你可以,但是你必須自己指定引數并以某種方式從依賴注入容器中決議它們,這通常是你不想做的。
uj5u.com熱心網友回復:
要將您的視圖模型注入到您的視圖中,您實際上需要在其建構式中執行它,在后面的代碼中,如下所示:
public partial class LoginPage : ContentPage {
public LoginPage(ILoginViewModel loginViewModel) {
BindingContext = loginViewModel;
InitializeComponent();
}
}
您還必須注冊使用依賴注入的視圖:
builder.Service.AddTransient<LoginPage>();
Afaik 你不能像你正在做的那樣在 XAML 中使用 DI 實體化視圖模型
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/483546.html
標籤:xamarin xamarin.forms 毛伊岛 .net-maui
