Service Locator

- 1 min

When to use ServiceLocator?

With ViewModels or Repositories you can use constructor dependency injection to provide a dependency. Constructor dependency injection requires that you construct the class. Fragments and Activities are examples of classes that you don’t construct and generally don’t have access to the constructor of.

Since you don’t construct the fragment, you can’t use constructor dependency injection to swap the repository test double to the fragment. Instead, you can use ServiceLocator pattern.

ServiceLocator Pattern

The Service Locator pattern is an alternative to Dependency Injection. It involves creating a singleton class called the “Service Locator”, whose purpose is to provide dependencies, both for the regular and test code. In the regular app code (the main source set), all of these dependencies are the regular app dependencies. For the tests, you modify the Service Locator to provide test double versions of the dependencies.

Not using Service Locator

alt text

Using a Service Locator

alt text

rss facebook twitter github gitlab youtube mail spotify lastfm instagram linkedin google google-plus pinterest medium vimeo stackoverflow reddit quora quora opensource