Service locator
Describes the service locator used for registering modular dependencies, when working with components in the Optimizely Content Management System (CMS) user interface.
The service locator ensures the system can be built modularly by registering loosely shared dependencies and controls global exposure without creating multiple global objects. Instead, a single global container object holds these dependencies.
- The
epi.dependencyimplementation is a lightweight service locator implementation to facilitate a decoupled client-side architecture. - The
epi/dependencyobject is a service location container responsible for managing the registration and resolution of dependencies. It is the hub class used to get references to dependent class implementations. Instead of using specific implementations in a class, useepi.dependencyto look up the implementation. This works like a dictionary, where the key is a string and the value is an object.
The service locator enables changing the dependency at runtime or performing unit testing by registering the dependency with the same key. There is no need to change (or even know what) objects are using that dependency.
Register dependencies
Dependencies can be registered as immediate object instances or as lazy references that load on first use.
Register dependencies by using an object instance.
var myServiceClass = new acme.services.MyServiceClass();
dependency.register("MyServiceClass", myServiceClass);A "lazy" dependency can also be registered where the class implementation is created when first resolved. The registered class is required and loaded by Dojo if needed.
dependency.register("MyLazyServiceClass", "acme.services.MyLazyServiceClass");Resolve dependencies
Resolving a dependency retrieves the registered implementation by its key.
To resolve dependencies, know the key with which the dependency is registered, then call resolve.
var service = dependency.resolve("MyServiceClass");An error occurs when resolving a key that is not registered. Because JavaScript does not have strongly typed objects, assume the service locator returns an object with the expected interface. When overriding a registered dependency, ensure the new object has the same interface as the previous one.
Updated 17 days ago
