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.
source share