Service Locator

Problem

You have classes that have dependencies on services whose concrete type is specified at design time.
ClassAHasDependenciesOnServiceAAndServiceB.png
Figure 1
The ClassA has dependencies on the ServiceA and the ServiceB.

This scenario has the following challenges:
  • To replace or update the dependencies, you need to change your class source code.
  • The concrete implementation of the dependencies must be available at compile time.
  • The classes are difficult to test in isolation because they have a direct reference to the services (therefore, you cannot replace the service implementations with mock implementations).

Forces

  • You want to decouple your classes from their services so the services can be replaced or updated with minimal changes, or no changes, to your classes' source code.
  • You want to be able to write classes that depend on services whose concrete implementation is not known at compile time.

Solution

Create a service locator that contains references to services and encapsulates the logic to locate them. In your classes, use the service locator to obtain service instances, as illustrated in Figure 2.
ClassAUsesServiceLocatorToGetAnInstanceOfServiceA.png
Figure 2
The ClassA uses the service locator to get an instance of the ServiceA.

The service locator is not responsible for instantiating the services; it is responsible for holding references to the services. The service locator provides a way to register services. After the service is registered, the service locator can find the service.

Note:
The service locator should provide a way to locate a service without specifying the concrete type. For example, it could use a string key or a service interface type.

Implementation Notes

The pattern can be implemented in several ways. For example, the service locator could be a singleton global instance that holds references to services.
In the Composite Web Application Block, composition containers contain a Services collection to hold references to services. Modules use this collection to register and locate services. For more information about how services are located in the Composite Web Application Block, see the section “Locating Services” in the Services topic.

Liabilities

  • There are more solution elements to manage.
  • You have to write additional code to add service references to the locator before your objects use it.
  • Your classes have an extra dependency on the service locator.
  • The source code has added complexity; this makes the source code more difficult to understand.

Related Patterns

  • Dependency Injection. The Dependency Injection pattern solves the same problems that the Service Locator pattern solves, but it uses a different approach.

Last edited Nov 20, 2007 at 12:37 PM by ejadib, version 2

Comments

No comments yet.