HomeDev GuideAPI Reference
Dev GuideAPI ReferenceUser GuideLegal TermsGitHubNuGetDev CommunitySubmit a ticketLog In

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 you can build the system modularly by registering dependencies shared loosely and lets you control global exposure without creating multiple global objects. Instead, a single global container object holds these dependencies.

  • The epi.dependency implementation is a lightweight service locator implementation to facilitate a decoupled client-side architecture.
  • The epi/dependency object 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, use epi.dependency to look up the implementation. It works like a dictionary, where the key is a string and the value is an object.

The server locator lets you change the dependency at runtime or perform unit testing so you can register the new dependency with the same key. You do not need to change (or even know what) objects are using that dependency.

Register dependencies

You can register dependencies by using an object instance.

var myServiceClass = new acme.services.MyServiceClass();
dependency.register("MyServiceClass", myServiceClass);

You can also register a "lazy" dependency, in which the class implementation is created when the dependency is first resolved. The registered class is required and loaded by Dojo if needed.

dependency.register("MyLazyServiceClass", "acme.services.MyLazyServiceClass");

Resolve dependencies

When resolving dependencies, you must know the registered key, then call resolve.

var service = dependency.resolve("MyServiceClass");

An error occurs if you try to resolve a key that is not registered. Also, because JavaScript does not have strongly typed objects, assume that the service locator will return an object with the interface you expect. If you override a registered dependency, you should ensure the object has the same interface as the previous one.