views:

904

answers:

2

I am trying to put all the pieces together for my MVVM Silverlight application and I see some blogs touch on Service Locators.

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

+1  A: 

Service locator is a design pattern similiar to dependency injection.

It allows a consumer to program against an Interface rather than a concrete class.

Take a look at the Common Service Locator hosted at CodePlex.

Mitch Wheat
+10  A: 

I've used ServiceLocator in combination with MVVM to enable declarative binding from the View to the ViewModel.

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

If you use an IoC container you'll probably create something like this:

public MyViewModel(IDataRepository repository)
{
}

The IoC container will push the IDataRepository instance into the object while constructing it.

If you use a ServiceLocator you will typically write code like this:

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

So in this case the ViewModel is pulling an instance of the IDataRepository interface from the ServiceLocator.

The ServiceLocator might be backed by a IoC container (but not necessary).

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

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

The MyViewModel might be created by a IoC container, but it's pulled into the View using data binding and a ServiceLocator.

I have a blog post about Dependency Injection, IoC and ServiceLocators in a Silverlihgt/MVVM context over at my blog.

Jonas Follesø