I want to get the Navigation from the ViewModel, therefore i need to get the INavigation using the constructor injection. Which simply worked fine with Xamarin.Forms registering INavigation with DI. But I cannot figure out how to achieve this with Maui.
var navigation = DependencyService.Get<INavigation>();
builder.Services.AddSingleton(navigation);
because first line shoulder return the navigation as this should be registered already by Maui Controls. Then I register this to the services for construction injection.
public MainViewModel(INavigation navigation) => _navigation = navigation;
I should be able to getting this as above. Similar implementation works for Xamarin.Forms but Maui returns DependencyService.Get<INavigation>();
null. Why is that? How can I achieve this?
Similar implementation works for Xamarin.Forms but Maui returns DependencyService.Get(); null.
This is because it call in different place in Xamarin.Forms and .Net Maui. The App.Current
is null before the builder.Build()
called, so the App isn't initialized.
In addition, You don't have to inject the INavigation for the ViewModel. You can get the instance directly:
App.Current.MainPage.Navigation
App.Current.Windows[0].Page.Navigation