Service Locator in MVVM

While doing MVVM one of the common problems to solve is to have the ViewModel consume entities that are “replaceable”. Let me give you an example so that you can better understand what I mean by “replaceable“. Let’s say you have a ViewModel that is using a DataAccess entity to get some data from a data store. You want to be able replace the DataAccess entity so that you can mock this entity for unit testing. Besides this you want to also be able to have some sample data while at design time. And not to forget, when at runtime you want the data access to connects to the database or whatever data store you are using.

In order to do solve this problem I use the ServiceLocator pattern. The Service Locator pattern is very simple. You have a RegisterService method where you register the instance of the service you want to provide and a GetService method which you would use to get the service you want.

Here is the signature of both methods

   1: public T GetService<T>()

   2:  

   3: public bool RegisterService<T>(T service)

And here is how to use them in code

   1: //get the data access service

   2: var dataAccess = GetService<IPeopleDataAccess>();

   3:  

   4: //Register the data access service

   5: vm.ServiceLocator.RegisterService<IPeopleDataAccess>(new PeopleDataAccess());

So for example to test the the ViewModel I can write a unit test like this

   1: MainViewModel viewModel = new MainViewModel();

   2: viewModel.ServiceLocator.RegisterService<IPeopleDataAccess>(new PeopleDataAccessMock());

   3:  

   4: Assert.AreEqual(viewModel.People.Count, PeopleDataAccessMock.PeopleCount,

   5:    "Invalid number of People returned");

   6: Assert.AreEqual(viewModel.People[0].Name, PeopleDataAccessMock.FirstPersonName,

   7:    "Invalid item in people list");

   8: Assert.AreEqual(viewModel.People[0].Surname, PeopleDataAccessMock.FirstPersonSurname,

   9:    "Invalid item in people list");

So basically in this unit test I am just creating a mock object and testing that my ViewModel is exposing the data from the data access (which is mocked so the data returned by this data access is known in the test context)

This is all cool but now how can I use this in WPF and MVVM. So the first question that people ask is how do I create the ViewModel and set it as the DataContext. And also who is responsible of assigning the services that the ViewModel will consume. In order to do this I use AttachedBehaviour and the Factory design pattern.

I created a simple attached property that accepts a type of a Factory that is responsible for creating the ViewModel and register whatever services it needs. The attached property is very simple, here is the code for it

   1: public class ViewModelLoader

   2: {

   3:     #region FactoryType

   4:  

   5:     /// <summary>

   6:     /// FactoryType Attached Dependency Property

   7:     /// </summary>

   8:     public static readonly DependencyProperty FactoryTypeProperty =

   9:         DependencyProperty.RegisterAttached("FactoryType", typeof(Type), typeof(ViewModelLoader),

  10:             new FrameworkPropertyMetadata((Type)null,

  11:                 new PropertyChangedCallback(OnFactoryTypeChanged)));

  12:  

  13:     /// <summary>

  14:     /// Gets the FactoryType property.  This dependency property 

  15:     /// indicates ....

  16:     /// </summary>

  17:     public static Type GetFactoryType(DependencyObject d)

  18:     {

  19:         return (Type)d.GetValue(FactoryTypeProperty);

  20:     }

  21:  

  22:     /// <summary>

  23:     /// Sets the FactoryType property.  This dependency property 

  24:     /// indicates ....

  25:     /// </summary>

  26:     public static void SetFactoryType(DependencyObject d, Type value)

  27:     {

  28:         d.SetValue(FactoryTypeProperty, value);

  29:     }

  30:  

  31:     /// <summary>

  32:     /// Handles changes to the FactoryType property.

  33:     /// </summary>

  34:     private static void OnFactoryTypeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)

  35:     {

  36:         FrameworkElement element = (FrameworkElement)d;

  37:         IFactory factory = Activator.CreateInstance( GetFactoryType(d) ) as IFactory;

  38:         if (factory == null)

  39:             throw new InvalidOperationException("You have to specify a type that inherits from IFactory");

  40:         element.DataContext = factory.CreateViewModel(d);

  41:     }

  42:  

  43:     #endregion

  44:  

  45: }

and you can use this in XAML like so

   1: <Window x:Class="ServiceLocatorSample.Main"

   2:     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

   3:     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

   4:     xmlns:vm="clr-namespace:MVVMHelper.Factory;assembly=MVVMHelper"

   5:     xmlns:fac="clr-namespace:ServiceLocatorSample.ViewModels.Factories"

   6:     Title="Main" Height="300" Width="300" vm:ViewModelLoader.FactoryType="{x:Type fac:MainViewModelFactory}">

Usually in the implementation of the factory I would check if the current state is at design time or runtime and accordingly register different services. Something like this

   1: public class MainViewModelFactory : IFactory

   2: {

   3:    public object CreateViewModel(DependencyObject sender)

   4:    {

   5:        var vm = new MainViewModel();

   6:        if (Designer.IsDesignMode)

   7:            vm.ServiceLocator.RegisterService<IPeopleDataAccess>(new DesignTimeData.DesignTimePeopleDataAccess());

   8:        else

   9:            vm.ServiceLocator.RegisterService<IPeopleDataAccess>(new PeopleDataAccess());

  10:        return vm;

  11:    }

  12: }

So with this factory at design time I would get Design time data showing in my designer but as soon as I run the app the actual data access (the real one that connects to the database) gets injected.

That’s it for today. Download the sample project and you will have a better idea of how all this works. Any questions or comments please let me know, I will be more than happy to answer🙂

P.S In the sample I have the full MVVMHelper assembly that I use in my everyday work with MVVM so you will also have stuff like Mediator and other things that I will be blogging about very soon🙂

Download the sample project

5 thoughts on “Service Locator in MVVM

  1. Using ServiceLocator is okay, but having VMs have a ServiceLocator property on which you register the services does not sounds too good to me. Why not use constructor injected dependencies, which you can easily setup in unit tests? Resolving VMs from container will have all constructor dependencies satistifed and will result to cleaner code :

    public class MainViewModel {
    public MainViewModel(IDataService dataService) {
    //ctor logic
    }
    }

    [TestFixture]
    public void Test() {
    var vm = new MainViewModel(new FakeDataAccess());
    }

  2. Pingback: Dew Drop – September 3, 2009 | Alvin Ashcraft's Morning Dew

  3. Pingback: Working with the WPF VSM in an MVVM friendly manner « C# Disciples

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s