advanced-service-locator
v1.0.0-dev.1
Published
Object oriented ServiceLocator for use with TypeScript or JS
Downloads
1
Maintainers
Readme
advanced-service-locator
Class based ServiceLocator for use with TypeScript or JS.
More about ServiceLocator pattern
Install
npm i advanced-service-locator
Import
//es5
const {ServiceLocator, ILocatable, ILocator} = require("advanced-service-locator");
//es6+ and ts
import {ServiceLocator, ILocatable, ILocator} from "advanced-service-locator";
Example classes
class TestClass implements ILocatable {
init(locator: ILocator): void {
//will be called after instantiation
}
getMessage(): string {
return "Hello from ServiceLocator!";
}
}
class TestClassCustom extends TestClass {
getMessage(): string {
return "This is custom message!";
}
}
Locate an instance
const locator = new ServiceLocator();
const a = locator.locate(TestClass);
Class mapping
const locator = new ServiceLocator();
locator.mapClass(TestClass).to(TestClassCustom);
const a = locator.locate(TestClass);
console.log(a.getMessage()); //will output "This is custom message!"
Map class as a singleton
const locator = new ServiceLocator();
locator.mapClass(TestClass).asSingleton();
const a = locator.locate(TestClass);
const b = locator.locate(TestClass);
console.log(a === b); //will output "true"
Recommend to use as a singleton
class Locator {
static readonly instance = new ServiceLocator();
}
const a = Locator.instance.locate(TestClass);