Xamarin 的 Prism,INavigationService 的依赖失败
Prism for Xamarin, dependency failed for INavigationService
我正在使用 PRISM 为 iOS 开发示例 Xamarin.Forms 应用程序。
但是当我尝试在 ViewModel 中使用 INavigationService 时,它失败了,提示接口 INavigationService 的依赖失败
我不知道我做错了什么,我们如何解决它或者它是 INavigationServices 注入中的错误。
谢谢
迪维基兰·拉维拉
这是代码
public App()
{
// The root page of your application
Prism = new PrismBootStrap();
Prism.Run(this);
}
public class PrismBootStrap : UnityBootstrapper
{
protected override Page CreateMainPage()
{
return new NavigationPage(Container.Resolve<HomePage>());
}
protected override void RegisterTypes()
{
Container.RegisterTypeForNavigation<HomePage, HomePageViewModel>();
}
}
public class HomePage : ContentPage
{
public HomePageViewModel ViewModel { get; set; }
public HomePage()
{
ViewModel = App.Prism.Container.Resolve<HomePageViewModel>();
Content = new StackLayout
{
Children = {
new Label { Text = "Hello ContentPage" }
}
};
}
}
public class HomePageViewModel : BindableBase
{
private readonly INavigationService _navigationService;
public HomePageViewModel(INavigationService navigationService)
{
_navigationService = navigationService; //Fails here
}
}
INavigationService 依赖于 ViewModelLocator 的使用。如果您不使用它,则无法注入该服务。不要手动解析您的 VM,而是使用附加的 ViewModelLocator.AutowireViewModel 属性。此外,你不想那样使用你的容器。使用 DI 时只需要一个组合根。
此外,我建议使用最新的 6.1 预览版。它有大量的导航改进。
我正在使用 PRISM 为 iOS 开发示例 Xamarin.Forms 应用程序。
但是当我尝试在 ViewModel 中使用 INavigationService 时,它失败了,提示接口 INavigationService 的依赖失败
我不知道我做错了什么,我们如何解决它或者它是 INavigationServices 注入中的错误。
谢谢 迪维基兰·拉维拉
这是代码
public App()
{
// The root page of your application
Prism = new PrismBootStrap();
Prism.Run(this);
}
public class PrismBootStrap : UnityBootstrapper
{
protected override Page CreateMainPage()
{
return new NavigationPage(Container.Resolve<HomePage>());
}
protected override void RegisterTypes()
{
Container.RegisterTypeForNavigation<HomePage, HomePageViewModel>();
}
}
public class HomePage : ContentPage
{
public HomePageViewModel ViewModel { get; set; }
public HomePage()
{
ViewModel = App.Prism.Container.Resolve<HomePageViewModel>();
Content = new StackLayout
{
Children = {
new Label { Text = "Hello ContentPage" }
}
};
}
}
public class HomePageViewModel : BindableBase
{
private readonly INavigationService _navigationService;
public HomePageViewModel(INavigationService navigationService)
{
_navigationService = navigationService; //Fails here
}
}
INavigationService 依赖于 ViewModelLocator 的使用。如果您不使用它,则无法注入该服务。不要手动解析您的 VM,而是使用附加的 ViewModelLocator.AutowireViewModel 属性。此外,你不想那样使用你的容器。使用 DI 时只需要一个组合根。
此外,我建议使用最新的 6.1 预览版。它有大量的导航改进。