Skip to content

ViewModel Locator

Neil McAlister edited this page Feb 7, 2017 · 2 revisions

The ViewModel Locator is the beating heart of Xalami. In here, you'll register all your services, ViewModels, and set up your Navigation service. By default, it can be found in the PCL project, under Mvvm/ViewModelLocator.cs.

Xalami uses MVVM Light as the IoC Container inside the ViewModel Locator, but there's no reason you couldn't swap out in your own. Any examples on this page assume you'll be using MVVM Light's SimpleIoc.

Initializing the Locator

In order to initialize the ViewModel Locator, all you need to do is run the following in the constructor:

ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);

Registering Services

Once the Locator has been initialized, registering your services is easy. Take a theoretical SettingsService that implements (an also theoretical) ISettingsService as an example:

SimpleIoc.Default.Register<ISettingsService>(() => new SettingsService());

What if your SettingsService's constructor depends on, say, your NavigationService? Well, you'd just initialize your NavigationService first and hold onto a reference, like so:

var navigationService = new NavigationService();
SimpleIoc.Default.Register<INavigationService>(() => navigationService); // You might as well register it while you're in here.
SimpleIoc.Default.Register<ISettingsService>(() => new SettingsService(navigationService)); // and done!

Registering ViewModels

Registering your ViewModels with the ViewModelLocator is what allows dependency injection in your ViewModels to work. If you have some MainViewModel for example, all you have to do is run something like this in your ViewModelLocator's constructor:

SimpleIoc.Default.Register<MainViewModel>();

Now, whenever the SimpleIoc receives a request for a MainViewModel, it'll inject all of that ViewModel's dependencies!

ViewModel Dependency Injection

Dependency Injection with ViewModels is easy. As long as you register your dependencies and your ViewModels with the ViewModelLocator, as explained above, all you need to do is include them in the ViewModel's constructor.

Let's say you have a MainViewModel, and you want it to take a dependency on your SettingsService and your NavigationService.

MainViewModel will look something like this.

public class MainViewModel : ViewModelBase
{
    private readonly ISettingsService _settingsService;
    private readonly INavigationService _navigationService;

    public MainViewModel(INavigationService navService, ISettingsService settingsService)
    {
       _settingsService = settingsService;
       _navigationService = navigationService;
    }
}

And then, in order for the IoC container to construct the ViewModel, you just have to instruct it to do so, like follows:

ServiceLocator.Current.GetInstance<MainViewModel>();

And that will return your ViewModel with all its dependencies fulfilled.

Clone this wiki locally