Service locator
Service location is one of the mechanisms employed in EPiServer, to ensure that the system can be built-in a modular manner. The reason for using a service locator is to have better control over what functionality can be exposed globally without creating many 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 service locator is used for registering dependencies shared in a loosely coupled fashion.
The "epi/dependency" object is a service location container and it is responsible for managing the registering and resolving of dependencies. It is the hub all classes will use to get references to dependent class implementations. Instead of using specific implementations in a class, use epi.dependency to look up the implementation. This works just like a dictionary, where the key is a string and the value is an object.
Another benefit of using the service locator is if you want to change the dependency at runtime or in order to do unit testing you just register the new dependency with the same key. You do not need to change or even know what objects are using that dependency.
Registering dependencies
Dependencies can be registered in several ways. The easiest is to register a dependency using an object instance.
var myServiceClass = new acme.services.MyServiceClass();
dependency.register("MyServiceClass", myServiceClass);
It is also possible to register a lazy dependency. This is where the class implementation will be created when first resolved. The registered class will be required and loaded by Dojo if needed.
dependency.register("MyLazyServiceClass", "acme.services.MyLazyServiceClass");
Resolving dependencies
When it comes to resolving dependencies all we need to know is the key it is registered with and then we can simply call resolve.
var service = dependency.resolve("MyServiceClass");
Trying to resolve a key which is not registered will throw an error. Also because JavaScript does not have strongly typed objects, assumptions need to be made that the service locator will always return an object with the interface you expect. It also means that if you override a registered dependency you should ensure that the new object has the same interface as the previous one.
Last updated: Jul 09, 2014