Updating the navigation service to handle ViewModel creation and dependency injection

Currently, in the TripLog app, each page is responsible for creating its own ViewModel instance. However, because we provide a ViewModel's dependencies through its constructor, we would have to manually resolve each dependency within the Page class and then pass them into the ViewModel instantiation. Not only is this going to be messy code, it is also difficult to maintain, and doesn't promote loose coupling. Since we have registered our ViewModels in our IoC container, we can completely remove the ViewModel instantiations from our Pages and set our navigation service up to handle resolving the ViewModels from the IoC container, automatically supplying their dependencies through constructor injection, as shown in the following steps:

  1. First, remove the code from the constructor of each Page that sets its BindingContext property to a new ViewModel instance.
  2. Next, update the NavigateToView private method in the XamarinFormsNavService to handle setting the ViewModels of the Pages automatically as they are navigated to. After the Page (View) is created using the Invoke method, simply get a new instance of the specified ViewModel and assign it to the BindingContext property of the Page:
      async Task NavigateToView(Type viewModelType)
{
// ...

var view = constructor.Invoke(null) as Page;

var vm = ((App)Application.Current)
.Kernel
.GetService(viewModelType);

view.BindingContext = vm;

await XamarinFormsNav.PushAsync(view, true);
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.156.202