Prism Xamarin Forms Navigation service, Dependency

2019-08-23 14:53发布

问题:

As Prism said,

To obtain the INavigationService in your ViewModels simply ask for it as a constructor parameter

https://prismlibrary.github.io/docs/xamarin-forms/Navigation-Service.html#getting-the-navigation-service

like this:

public SpeakPageViewModel(INavigationService navigationService) : base(navigationService)

{

_navigationService = navigationService;

}

and I want to use ITextToSpeech interface as Prism sample :

public MainPageViewModel(ITextToSpeech textToSpeech)
{
    _textToSpeech = textToSpeech;
    SpeakCommand = new DelegateCommand(Speak);
}

https://prismlibrary.github.io/docs/xamarin-forms/Dependency-Service.html#use-the-service

The problem is: when add another parameter to the constructor, the navigation doesn't work.

public SpeakPageViewModel(ITextToSpeech textToSpeech, INavigationService navigationService) : base(navigationService)
        {
            _navigationService = navigationService;
            _textToSpeech = textToSpeech;
        }

project file : http://www.mediafire.com/file/nl6dx5c4mc3mg63/FirstPrismApp.rar

回答1:

Prism 7 changed this behavior as it is actually an anti-pattern to rely on a secondary container. You simply need to register your TextToSpeech service in the IPlatformInitializer like:

public class iOSInitializer : IPlatformInitializer
{
    public void RegisterTypes(IContainerRegistry containerRegistry)
    {
        containerRegistry.Register<ITextToSpeech, TextToSpeech_iOS>();
    }
}