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.
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.
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");