Home > C#, Mobile Services, MVVM, Windows Phone, WinRT > How to correctly use the Mobile Services SDK with MVVM in Universal Windows apps

How to correctly use the Mobile Services SDK with MVVM in Universal Windows apps

07/10/2014

If we want to use an Azure Mobile Service in our Universal apps, we can take advantage of the Add | Connected Service menu command. In this way, a static reference to a MobileServiceClient instance is added to the App.xaml.cs file.

However, if we’re following the MVVM pattern, this approach isn’t correct: we surely need to access the client from ViewModels, and so in this case we should reference the App class.

The solution is simple. Suppose we have added the MVVM Light Toolkit to the project. We can leverage the ViewModelLocator class to register an instance of the client:

SimpleIoc.Default.Register<IMobileServiceClient>(() =>
{
    var client = new MobileServiceClient(
        applicationUrl: "",
        applicationKey: "");

    return client;
});

We use an overload of the Register method that is able to create the instance that must be returned when the given type is resolved. In this case, we create the MobileServiceClient specifying the Service Url and the Application Key.

Doing so, we can pass a reference to the client to our ViewModels:

private IMobileServiceClient client;

public MainViewModel(IMobileServiceClient client)
{
    this.client = client;
    // ...
}

In this way, the MVVM pattern is respected and we can use the Mobile Service in our ViewModels as we expect to do.

%d bloggers like this: