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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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:
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:
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.
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.