ServiceLocator is a simple dependency injection container for TypeScript.
You can install ServiceLocator via npm:
npm install tiny-sl
import ServiceLocator from "@types/service-locator";
class MyService {
doSomething() {
console.log("doing something...");
}
dispose() {
console.log("disposing...");
}
}
let sl = ServiceLocator.instance;
sl.registerSingleton(MyService, new MyService());
let myService = sl.get(MyService);
myService.doSomething(); // doing something...
sl.unregister(MyService); // disposing...
// (or)
// sl.reset(); // disposing...
Returns the instance of the ServiceLocator.
Get the instance of a registered service.
-
type
: The type of the service. - Returns: The instance of the service.
- Throws: Error if the service registration is not found.
Register a singleton service.
-
type
: The type of the service. -
service
: The instance of the service. - Throws: Error if the service is already registered.
Register a lazy singleton service.
-
type
: The type of the service. -
factory
: The factory function to create the service instance. - Throws: Error if the service is already registered.
Register a factory service.
-
type
: The type of the service. -
factory
: The factory function to create the service instance. - Throws: Error if the service is already registered.
Unregister a service.
-
type
: The type of the service. - Throws: Error if the service registration is not found.
Reset the ServiceLocator.
-
params.dispose
: Whether to dispose services before resetting. Default istrue
.
Reset a lazy singleton service.
-
type
: The type of the service. - Throws: Error if the service registration is not found.
This package is licensed under the MIT License.