Why use splat Locator.CurrentMutable for routing in Xamarin Forms

95 views Asked by At

I found a sample Xamarin forms project used for login and registration (not my code, just trying to understand why behind it).

The constructor for the App class calls the following code:

    // Services
    Locator.CurrentMutable.RegisterLazySingleton<IRoutingService>(() => new ShellRoutingService());

    // ViewModels
    Locator.CurrentMutable.Register(() => new LoginViewModel());

The ShellRoutingService has the following code:

public class ShellRoutingService : IRoutingService
{
    public ShellRoutingService()
    {
    }

    public Task NavigateTo(string route)
    {
        return Shell.Current.GoToAsync(route);
    }

    public Task GoBack()
    {
        return Shell.Current.Navigation.PopAsync();
    }

    public Task GoBackModal()
    {
        return Shell.Current.Navigation.PopModalAsync();
    }
}

Is calling the NavigateTo in the ShellRoutingService from my viewmodel different than simply calling Shell.Current.GoAsync from my viewmodel? Why would one use NavigateTo in one place and Shell.Current.GoAsync in another place?

What does registering the LoginViewModel do, and why is it necessary?

1

There are 1 answers

0
Guangyu Bai - MSFT On

The reason for using Locator.CurrentMutable for routing in Xamarin Forms is to register and resolve dependencies in the application. Specifically, the Locator is being used to register two services: the IRoutingService and the LoginViewModel. Registering the IRoutingService allows the application to have a routing mechanism that is used for navigation between pages in the application.

Is calling the NavigateTo in the ShellRoutingService from my viewmodel different than simply calling Shell.Current.GotoAsync from my viewmodel?

The NavigateTo method uses the Shell.Current.GoToAsync(route); code, so this is the same with Shell.Current.GoToAsync.