Try our conversational search powered by Generative AI!

Loading...

Recommended reading 

Table of Contents

Introduction

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 that have better control over what functionality can be exposed globally without creating many global objects. Instead we have a single global container object which holds these dependencies.

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 we want to change the dependency at runtime or in order to do unit testing we just register the new dependency with the same key. We 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.

CopyJavaScript
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.

CopyJavaScript
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.

CopyJavaScript
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.

Do you find this information helpful? Please log in to provide feedback.

Last updated: Mar 21, 2013

Recommended reading