Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of a Service Locator in a Silverlight MVVM app?

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?

like image 923
jdiaz Avatar asked Dec 10 '22 22:12

jdiaz


2 Answers

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.

like image 142
Jonas Follesø Avatar answered Jan 11 '23 22:01

Jonas Follesø


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.

like image 32
Mitch Wheat Avatar answered Jan 11 '23 23:01

Mitch Wheat