Dislocator
A Service Locator implementation for JavaScript.
Installation
$ npm install dislocator
Usage
A ServiceLocator is a registry for services. It can be passed around in your application and help you make more decoupled applications, as well as making swapping services out when testing code.
// Creating a service locator instance; const serviceLocator = ; serviceLocator; serviceLocator // Using the service locator { const greeter = serviceLocatorgreeter; console;} ; // logs: Hello World!
class Dislocator
Default export from the CJS and ESM builds as well as in the UMD build when used
in CJS or AMD contexts. Accessible on window.Dislocator
if loaded in the
browser without a module loader.
constructor()
The constructor accepts no options.
const serviceLocator = ;
register(name: string, serviceCreator:any) => this
Method for registering a service.
The name
must be a string that contains only letters (both upper- and
lowercase) and numbers.
The serviceCreator
argument can be a literal value (e.g. an object) or a
function. Functions passed as serviceCreator
s will not be invoked until the
service is requested; meaning that serviceCreator
functions must return the
service instance synchroniuosly.
serviceLocator;serviceLocator;
serviceCreator
functions get passed a reference to the Dislocator instance as
the only argument.
serviceLocator;
The register
methods can be chained as the dislocator instance is returned.
serviceLocator ;
get(name: string) => any
Returns an instance of the requested service.
serviceLocator;
Services can also be retrieved through getters on the Dislocator instance.
serviceLocator === serviceLocatormyService; // => true
If you attempt to retrieve a service that is not registered both methods will result in an Error being thrown.
try serviceLocator; catch e // e: `Error: No registration named "noSuchService"`
Dislocator does circular dependency detection when instantiating services.
const serviceLocator = ; serviceLocator ; try serviceLocator; catch e // e: `Error: Circular dependency detected (serviceA -> serviceB -> serviceA)`
unregister(name: string) => this
Remove a registered service and any instantiated versions of it. Can be chained.
serviceLocator ;
isRegistered(name: string) => boolean
Checks if a service is registered.
serviceLocator; // => false serviceLocator; serviceLocator; // => true serviceLocator; serviceLocator; // => false
names() => array<string*>
Returns a list of names of the registered services.
serviceLocator ; serviceLocator; // => ['someService', 'anotherService']
use(serviceProvider: function) => this
Allows you to modularize functions that register services.
const serviceLocator = ; serviceLocator; serviceLocator; // File: services/myService.js const MyService = ; module { serviceLocator;};
License
MIT