Skip to content
This repository has been archived by the owner on Aug 27, 2020. It is now read-only.

DependencyServiceWrapper

Mark Smith edited this page Sep 2, 2016 · 2 revisions

DependencyServiceWrapper

The DependencyServiceWrapper is a simple wrapper around the Xamarin.Forms static class DependencyService. It makes the class mockable for unit tests and reduces the coupling to the Forms framework in your View Models.

This implements the IDependencyService interface.

Alternatively, consider leveraging a 3rd party DI container or locator.

Usage

To use this wrapper, create an instance, or track the one returned from XamUInfrastructure.Init and cache it off as a IDependencyService in your code. Then use this to resolve dependencies.

public class MyViewModel
{
   IDependencyService ds;

   // Pass in some implementation - could be a mock for testing.
   public MyViewModel(IDependencyService ds) {
      this.ds = ds;
   }

   void OnError() {
      ds.Get<IMessageVisualizerService>()
          .Show("Error", "Houston, we have a problem", "OK);
   }
}

.. when you create the view model - pass in this implementation for runtime use.

public class MainPage : ContentPage
{
   public MainPage()
   {
      BindingContext = new MyViewModel(new DependencyServiceWrapper());
   }
}

.. but for unit testing, pass in a mock:

class MockDependencyService : IDependencyService
{
   ...
}

[TestMethod]
public void TestMethod()
{
   var mock = new MockDependencyService();
   var vm = new MyViewModel(mock);

  ...
}