Five New Optimizely Certifications are Here! Validate your expertise and advance your career with our latest certification exams. Click here to find out more
Five New Optimizely Certifications are Here! Validate your expertise and advance your career with our latest certification exams. Click here to find out more
The service locator ensures that the system can be built-in a modular manner by registering dependencies shared in a loosely coupled fashion, and lets you control exposure of globally without creating many global objects; instead, a single global container object holds these dependencies.
Server locator lets you change the dependency at runtime or to 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.
You can register dependencies by using an object instance.
var myServiceClass = new acme.services.MyServiceClass();
dependency.register("MyServiceClass", myServiceClass);
You also can register a "lazy" dependency 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");
When it comes to resolving dependencies, you need to know the key with which it is registered, 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 that the new object has the same interface as the previous one.
Last updated: Sep 21, 2015