tiny-sl
v1.0.0
Published
ServiceLocator is a simple dependency injection container for TypeScript.
Downloads
2
Readme
Service Locator
ServiceLocator is a simple dependency injection container for TypeScript.
Installation
You can install ServiceLocator via npm:
npm install tiny-sl
Usage
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...
API
ServiceLocator
instance: ServiceLocator
Returns the instance of the ServiceLocator.
get<T>(type: new () => T): T
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.
registerSingleton<T>(type: new () => T, service: T): void
Register a singleton service.
type
: The type of the service.service
: The instance of the service.- Throws: Error if the service is already registered.
registerLazySingleton<T>(type: new () => T, factory: () => T): void
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.
registerFactory<T>(type: new () => T, factory: () => T): void
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<T>(type: new () => T): void
Unregister a service.
type
: The type of the service.- Throws: Error if the service registration is not found.
reset(params?: { dispose: boolean }): void
Reset the ServiceLocator.
params.dispose
: Whether to dispose services before resetting. Default istrue
.
resetLazySingleton<T>(type: new () => T): void
Reset a lazy singleton service.
type
: The type of the service.- Throws: Error if the service registration is not found.
License
This package is licensed under the MIT License.