What is the purpose of a service locator in a Silverlight MVVM application?

I am trying to compile all the parts for my Silverlight MVVM application, and I can see that some blogs relate to Locators.

What is a service locator and when should it be used?

+4
source share
2 answers

I used ServiceLocator in conjunction with MVVM to enable declarative binding from View to ViewModel.

ServiceLocator is pull-based, while IoC containers are push-based. For instance:

If you are using an IoC container, you are likely to create something like this:

public MyViewModel(IDataRepository repository) { } 

The IoC container will push the IDataRepository instance into the object when it is created.

If you use ServiceLocator, you usually write this code:

 public MyViewModel() { _repository = ServiceLocator.Instance.DataRepository; } 

So, in this case, the ViewModel pulls out an instance of the IDataRepository interface from the ServiceLocator.

ServiceLocator may be supported by the IoC container (but not required).

The advantage of this is that you can add the ServiceLocator as a resource to your App.xaml file and then declare it declaratively from the views.

 <UserControl DataContext="{Binding Path=MyViewModel, Source={StaticResource serviceLocator}}">...</UserControl> 

MyViewModel can be created by the IoC container, but it gets pulled into the view using data binding and ServiceLocator.

I have a blog post about dependency injection, IoC and ServiceLocators in the context of Silverlihgt / MVVM in my blog.

+13
source

A service locator is a design pattern similar to dependency injection.

It allows the consumer to program against an interface rather than a specific class.

Take a look at the generic service locator hosted in CodePlex.

+1
source

All Articles