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>()


   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>();


   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());


   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


   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)));


  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:     }


  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:     }


  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:     }


  43:     #endregion


  45: }

and you can use this in XAML like so

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

   2:     xmlns=""

   3:     xmlns:x=""

   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

Animations and MVVM

This week I was asked from a colleague of mine, ‘How do I fire a command once a storyboard has completed?’. Do we have to break the MVVM here and write code behind. The answer is simple, HELL NO….

Attached Behavior to the rescue. Basically we can do this task by using an attached property, that will hook up to the Completed event of the storyboard and fire the command for us on the ViewModel. Here’s how to do this

   1: var timeline = d as Timeline;

   2: if (timeline != null && !timeline.IsFrozen)

   3: {

   4:    timeline.Completed += delegate

   5:    {

   6:        ICommand command = GetCommand(d);

   7:        object param = GetCommandParameter(d);


   9:        if(command != null && command.CanExecute( param ))

  10:            GetCommand(d).Execute(GetCommandParameter(d));

  11:    };

  12: }

and here is how to use this in XAML

   1: <EventTrigger RoutedEvent="ButtonBase.Click">

   2:     <BeginStoryboard>

   3:         <Storyboard cmds:CommandStoryboard.Command="{Binding Close}" >

   4:             <DoubleAnimation Storyboard.TargetName="border" Storyboard.TargetProperty="Height" 

   5:                          DecelerationRatio="1.0" Duration="0:0:0.5" To="0"/>

   6:         </Storyboard>

   7:     </BeginStoryboard>

   8: </EventTrigger>

In the sample application (that is provided below with this article) shows how to animate some item in an items control and when the animation is completed the Storyboard executes a command that actually removes the item from the binding list.

I also created another simple class so that you can execute a Command from an EventTrigger. This is very handy since sometimes we want to execute a Command on a VM when some arbitrary RoutedEvent is raised. Here is the code for that

   1: public class CommandTimeline : Storyboard

   2: {

   3:     protected override Duration GetNaturalDurationCore(Clock clock)

   4:     {

   5:         return new Duration(TimeSpan.FromTicks(1));

   6:     }


   8:     protected override Freezable CreateInstanceCore()

   9:     {

  10:         return new CommandTimeline();

  11:     }

  12: }

and here is how to consume it

   1: <EventTrigger RoutedEvent="FrameworkElement.Loaded">

   2:     <BeginStoryboard>

   3:         <cmds:CommandTimeline cmds:CommandStoryboard.Command="{Binding Test}" />

   4:     </BeginStoryboard>

   5: </EventTrigger>

As you can see this reuses the attached behavior that is used on normal storyboards. The only difference between a Storyboard and a CommandTimeline is that a CommandTimeline returns a Duration of 0 so the Completed event gets raised immediately.

PLEASE NOTE: This can be only used in an event trigger. When this is used with DataTriggers etc you will get an exception saying that the Trigger cannot be sealed. This happens because you cannot hook up to the Completed event of a storyboard in a DataTrigger/Trigger. In order to workaround this I use AttacedRoutedEvents so that I can have EventTriggers executing my commands.

Download the sample app + source code

Sync Multi Select Listbox with ViewModel

Today one of my colleagues at Infusion asked me how he could sync up the selection of a ListBox with his ViewModel. WPF supports already single mode selection via the ICollectionView yet when it comes to MultiSelect there is no out of the box support in WPF.

Attached Properties to the rescue ….. :)

I quickly when in my VS and wrote up a simple Attached property that hooks to the SelectionChanged event of the ListBox and populates a list of selected items to the ViewModel.

This is how the attached property looks like

   1: #region SelectedItems


   3: /// <summary>

   4: /// SelectedItems Attached Dependency Property

   5: /// </summary>

   6: public static readonly DependencyProperty SelectedItemsProperty =

   7:     DependencyProperty.RegisterAttached("SelectedItems", typeof(IList), typeof(ListBoxHelper),

   8:         new FrameworkPropertyMetadata((IList)null,

   9:             new PropertyChangedCallback(OnSelectedItemsChanged)));


  11: /// <summary>

  12: /// Gets the SelectedItems property.  This dependency property 

  13: /// indicates ....

  14: /// </summary>

  15: public static IList GetSelectedItems(DependencyObject d)

  16: {

  17:     return (IList)d.GetValue(SelectedItemsProperty);

  18: }


  20: /// <summary>

  21: /// Sets the SelectedItems property.  This dependency property 

  22: /// indicates ....

  23: /// </summary>

  24: public static void SetSelectedItems(DependencyObject d, IList value)

  25: {

  26:     d.SetValue(SelectedItemsProperty, value);

  27: }


  29: /// <summary>

  30: /// Handles changes to the SelectedItems property.

  31: /// </summary>

  32: private static void OnSelectedItemsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)

  33: {

  34:     var listBox = (ListBox)d;

  35:     ReSetSelectedItems(listBox);

  36:     listBox.SelectionChanged += delegate

  37:     {

  38:         ReSetSelectedItems(listBox);

  39:     };

  40: }


  42: #endregion


  44: private static void ReSetSelectedItems(ListBox listBox)

  45: {

  46:     IList selectedItems = GetSelectedItems(listBox);

  47:     selectedItems.Clear();

  48:     if (listBox.SelectedItems != null)

  49:     {

  50:         foreach (var item in listBox.SelectedItems)

  51:             selectedItems.Add(item);

  52:     }

  53: }

and here is how you would use it in the XAML

   1: <ListBox ItemsSource="{Binding MyData}" Grid.Column="1" local:ListBoxHelper.SelectedItems="{Binding SelectedData}"

   2:                  SelectionMode="Extended"/>

As you can see all you have to set is the List you want to populate in the ViewModel and the rest is taken care of by the Attached Property.

Please Note: This code was implemented quickly without any testing to prove an implementation idea, so please do review it before putting it in production :)

Download the source code

Mediator v2 for MVVM WPF and Silverlight applications

This last 2 weeks, us WPF Disciples have been talking a lot about the Mediator pattern for MVVM applications. Me and Josh Smith revised my previous Mediator implementation and found some problems with it.

Problem: There was a memory leak. Once a Mediator subscribes for one or more messages it would be kept in memory since the Mediator was holding a reference to the ViewModel.
Solution: We could have just exposed an unregister method so that when you call this method the Mediator would release the instance of the ViewModel. But sometimes it is hard to know when a ViewModel is going to die… So we went a step further and created the WeakAction. The WeakAction stores the instance of the ViewModel in a WeakRefence thus the ViewModel can be garbage collected without any problem and once it does get garbage collected the Mediator automatically removes that ViewModel registration from the list.

While we were at it we PIMPED the Mediator API :) We added 2 approaches to subscribe to the Mediator and we also added support for (thanks to David Anson suggestion) strongly typed parameters.

So now the Mediator offers 2 methods of registration, a declarative way of registering and an imperative way as well.

The Declarative approach. (Supported in WPF and Silverlight)

This approach uses attributes so that you can decorate the messages that act as subscribers for messages.Here is an example

   1: /// <summary>

   2: /// Subscribe to Message1

   3: /// </summary>

   4: /// <param name="message">The message to be passed</param>

   5: [MediatorMessageSink(MediatorMessages.Message1, ParameterType = typeof(SomeData))]

   6: public void Test(SomeData data)

   7: {

   8:     MessageBox.Show(data.Text + "\nReceived by: ColleagueA");

   9: }

So you just have to decorate your method with MediatorMessageSink attribute and the Method will get invoked every time a message is broadcasted via the Mediator.

As you can see the Mediator also supports strongly typed parameters. In order to do so you have to specify the ParameterType property on the attribute as shown in the sample code above. You can pass 0 or 1 parameters. If you don’t have any parameters just ignore the ParameterType (since this is an named Property and you can just not set it )

When using the declarative approach you must register the instance of the ViewModel to the Mediator. This is just one line of code in the ViewModel constructor. Here is how you do that

   1: public ColleagueA()

   2: {

   3:     //Register all decorated methods to the Mediator

   4:     Mediator.Register(this);

   5: }

This will inspect all methods of the ViewModel and look for the MediatorMessageSink attribute and register the appropriate methods to the Mediator. If you are going to have a base class for the ViewModels in your project and you can put this in the constructor of your base class. As simple an that.


The Imperative approach. (Supported in WPF ONLY)

If you do not want to use the attribute based registration we offer an imperative approach where you specify a method to be registered to a specific message. This implementation is exactly as it was in the old Mediator yet now it supports strongly typed parameters.

Here is how you can use this in your code

   1: public ColleagueC()

   2: {

   3:     //Register a specific delegate to the Mediator

   4:     Mediator.Register(MediatorMessages.Message1,

   5:         (Action<SomeData>)

   6:         delegate(SomeData x) 

   7:         {

   8:             Test = x.Text;

   9:             MessageBox.Show(x.Text + " \nReceived by: ColleagueC"); 

  10:         });

  11: }

This method is supported in WPF only since in Silverlight you cannot call an anonymous method (via reflection). If you try to use this method in Silverlight you will get an InvalidOperationException saying “This method is not supported in Silverlight”.



I packaged the Mediator in a class library so that you can go ahead and add a reference and reuse this library in your day to day projects.As always feedback is much appreciated.

Download MediatorLib + Sample application

[MVVM + Mediator + ACB = cool WPF App] – The MVVM

The Model View ViewModel is quite a hot subject right now in the WPF community. If you never read about MVVM I suggest that you read the following before you continue reading

- Introduction to Model/View/ViewModel pattern for building WPF apps by John Gossman (MVVM daddy)

- WPF & Silverlight Line of Business UI Design Pattern by Karl Shifflett

- WPF Apps With The Model-View-ViewModel Design Pattern by Josh Smith


MVVM in my sample app

Let me start by showing you a class diagram of the application structure


As you can see in the image above we have 3 layers. We have our Views, the ViewModels and the Models. (Please note that you can have n Tiers yet I am focusing just on 2 Tiers here, View and ViewModel….)

The View

The view is the “component” that renders the data on screen. This should be done all in XAML and not in C#. Why? Well UIs are much better built in a declarative fashion instead of an imperative one.

The View can be developed by a designer by using tools such as Blend and should not require any need from a developer. In the View the designer should express his artistic creativeness without any constrains from the developers.

Besides this when you put code in the View, this code is super hard to Unit test. From experiance I must say that 99% of the code written in the UI layer is never tested.

Ok so the designer sets the colors of the buttons etc… BUT!!!!

A - what about the data?  From where can the designer get the data without having C# knowledge?
B – what about actions/events? How can a designer specify that when the button is clicked something should happen?

Well my friends that is the power of the WPF Databinding and the MVVM!

The ViewModel

The ViewModel is just a simple class (That has no coupling with the View and 100% unit testable). The ViewModel exposes data that the View can use to render the UI. Besides this the ViewModel also has Commands that the View can use to invoke actions. I will demo 2 pages that I created in the Sample App that explain how the ViewModel does this job.

A – what about the data?


To show you how the view renders data exposed by the ViewModel we will take the example in the screen shot above.

The ViewModel involved here is called ProjectListViewModel and the View is called ProjectList.xaml

The ViewModel exposes the data via a property called Projects. The property is shown below

   1: ObservableCollection<WPFDisciples.Backend.ProjectDetails> projects

   2:     = new ObservableCollection<WPFDisciples.Backend.ProjectDetails>();

   3: public ObservableCollection<WPFDisciples.Backend.ProjectDetails> Projects

   4: {

   5:     get { return projects; }

   6: }

As you can see this is simply a normal CLR property (not a DependencyProperty ). In this case the real magic is not in the property as such but in the type of Collection. Since the property exposes an ObservableCollection<T>, the databinding engine will listen to collection changed notifications and update the rendered data according.

This is how we bind to the data in the View’s XAML

   1: <ListView ItemsSource="{Binding Projects}"

In this XAML we are doing List binding. We are specifying to the ListView that it should bind to the Projects property. The question is the Projects property of what object?

By default the source of a Binding is the DataContext of the element. In this case the DataContext will be the ViewModel. We specify that in the constructor of the View. There are many other nicer ways of doing this initialization of ViewModel in the View such as by using Onyx(this is a super cool WPF project!!!!! you must try it) or Dependency injection (such as in PRISM)

   1: public ProjectList()

   2:         {

   3:             InitializeComponent();


   5:             var viewModel = new ProjectListViewModel(Dispatcher);
   6:             DataContext = viewModel;

   7:         }

B – what about actions/events?

So let’s say you have a button and you want something to happen when the user clicks the button. Well the approach that we have been using in .Net is events. So a button would have a Click event and you would register an event handler for the event. Yet is this the right approach? Can a designer do this? Can you easily unit test such a method? Well I would say not really or better not easily…

A much better method has been introduced in WPF, the Commands. With commands you can delegate the work (such as a Click event) to the ViewModel. By doing so, the Designer can just specify what command to use for a button and viola he is done. Besides that the ViewModel can be unit tested much easier.

enter data

The example I picked from the sample app is the Save button to add a new Project. This can be found ProjectDetailsViewModel.cs

Here is the code that I used to expose the Command

/// <summary>
/// Gets a Command to save the current project
/// </summary>
public SimpleCommand SaveProject { get; private set; }

Where SimpleCommand is a class that implements the ICommand interface. For more info on this visit this post.

and here is the code for the Command.

SaveProject = new SimpleCommand
                ExecuteDelegate = Save,
                //Can execute only if there are no errors
                CanExecuteDelegate = x => String.IsNullOrEmpty(Project.Error)


This article should have given you a basic idea of how the M V VM works… Next post will discuss how to overcome some of the problems with MVVM. I will show you how you have to start thinking in databinding so that you implement MVVM in a proper way.


[MVVM + Mediator + ACB = cool WPF App] – Intro

Finally I managed to spare some time and build a WPF sample application to showcase the use of MVVM + Mediator and also how AttachedCommandBehaviours can be used to further reduce (or better eliminate) C# code in XAML code behind files. I am also using one of my favorite WPF libraries FluidKit. In the app I create my own 3D transition for the FluidKit TransitionPresenter (I will be posting a whole post on this).

I will be posting at least 4 posts


- MVVM and the Mediator pattern

- FluidKit CoverFlow and FluidKit TransitionPresenter

- Using AttachedCommandBehaviours

Here are some teaser screenshots of the application in action :)

Screen1 Screen2

Screen3 Screen4


Setup of application environment

This application uses a SQL Database so you will need an instance of SqlServer 2005 running (you can use SqlServer Express).

I packaged the database as a backup so all you need to do is restore the database from the SqlServer Management Studio Express (this is your easiest option). If you don’t have this I suggest you download it, it’s free.

To restore the database file (WPFDisciplesDB.bak) follow these steps

- First of all download the database file from here.

- Right click on the Databases folder in the SQL Server Management Studio Express and select Restore database

Step 1

This will open a dialog for you. In the Restore Database dialog enter a name for the database in the “To database” text field > Select “From device” radio button and browse for the WPFDisciples.bak that you downloaded. The file will appear in the list. Tick the checkbox (which is un checked by default) and press ok.

Step 2 

Now that we have our database set up all we need to do is specify in the app.config the connection string of the new database and we are done.

Stayed tuned because this should be real fun :)

aaaa I nearly forgot… The data in the database is not the full version… I will add more projects from the mighty WPF Disciples as time goes by…. Will continue updating the download link here (and put a comment or something to show you that I updated the db version)

Download Full Source Code from HERE

Just in case you missed it, here is a copy of the database