TheDeveloper
TheDeveloper

Reputation: 1217

Xamarin Forms Prism: Is INavigationService necessary to be passed in constructor? Any other way apart from constructor injection

For prism framework in xamarin forms, to navigate from one view to another, is it mandatory to implement constructor inject and pass INavigationService in ViewModel's constructor?

I Can perform Navigation when I pass INavigationService as

public SomeViewModel(INavigationService navigationService)
{
  _navigationService.NavigateAsync("SomeOtherPage");
}

But when I try to resolve whenever its needed, it doesn't work

public SomeViewModel(INavigationService navigationService)
    {
      ContainerProvider.Resolve<T>();// ContainerProvider is IContainerProvider
    }

Is there any other way to access INavigationService apart from constructor injection in every Viewmodel

Upvotes: 0

Views: 427

Answers (1)

Dan Siegel
Dan Siegel

Reputation: 5799

What you’re describing is an anti pattern, and generally just poor design. It also will not work because the Navigation Service is a very special service. It is created especially for each ViewModel as the Navigation Service must have the context of the Page you are navigating from. Without it, it would only work for resetting the Navigation Stack. To attempt to resolve the Navigation Service any other way in the ViewModel would likely break the MVVM design pattern.

If you want to use the Navigation Service you must inject it via the constructor. You may also simply use XAML Navigation in Prism 7.1. You can see a sample with the Prism Tests. You can also see this in practice in this demo app.

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:xaml="clr-namespace:Prism.Navigation.Xaml;assembly=Prism.Forms"
             Title="{Binding Title}"
             x:Class="Prism.DI.Forms.Tests.Mocks.Views.XamlViewMockA">
    <Button x:Name="testButton" Command="{xaml:NavigateTo 'XamlViewMockB'}">
        <Button.CommandParameter>
            <xaml:NavigationParameters>
                <xaml:NavigationParameter Key="Foo" Value="Bar"/>
            </xaml:NavigationParameters>
        </Button.CommandParameter>
    </Button>
</ContentPage>

Upvotes: 1

Related Questions