Dependency Injection¶
The @typeix/di package: injector hierarchy, provider types, method interceptors, injector scopes and metadata caching.
Dependency Injection (DI) is a design pattern used to implement IoC. It allows the creation of dependent objects outside of a class and provides those objects to a class through different ways. Using DI, we move the creation and binding of the dependent objects outside of the class that depends on them.
Learn more about the dependency injector in the fundamentals section.
You can use the DI library in any of your projects.
Installing¶
npm i @typeix/di --save
Decorators¶
| Decorator | Info |
|---|---|
@Injectable() | Specifies that Typeix can use this class in the DI system. Decorators can be used on classes only. |
@Inject() | Specifies DI system, which object to provide when object is created. If there is no provider defined DI will throw error with explanation. |
@AfterConstruct() | Specifies DI system, what to execute immediately after object is created. |
@CreateProvider() | Specifies DI system, to create new provider on injection point. This will create new object even if there is a provider defined in parent Injector. |
Interceptors¶
An interceptor pattern is a software design pattern that is used when software systems or frameworks want to offer a way to change, or augment, their usual processing cycle.
import {Injectable, Injector, Inject, Interceptor, Method, createMethodInterceptor} from "@typeix/di";
@Injectable()
class LoggerInterceptor implements Interceptor {
@Inject() logger: Logger;
async invoke(method: Method): Promise<any> {
const result = await method.invoke();
this.logger.info(method.decoratorArgs.message, method.methodArgs, result);
return result;
}
}
export function Logger(message) {
return createMethodInterceptor(Logger, LoggerInterceptor, {message});
};
@Injectable()
class ChildService {
@Logger("Logging ChildService.getName result: ")
getName(): string {
return this.name;
}
}
Usage¶
In order to create an object of some class you need to define class as @Injectable and injection points via @Inject, then when creating an instance you need to provide DI what to construct and which providers to create.
import {Injectable, Injector, Inject} from "@typeix/di";
@Injectable()
class NameService {
@Inject("name") private name: string;
getName() {
return this.name;
}
}
@Injectable()
class ChildService {
@Inject() nameService: NameService;
getName(): string {
return this.nameService.getName();
}
}
Injector.createAndResolve(ChildService, [
{provide: "name", useValue: "Igor"},
NameService
]).then(injector => {
let service = injector.get(ChildService);
return service.getName();
});
Provider Types¶
There are three type of providers class, value and factory provider, functions inside providers array are converted to class providers.
There are three types of providers in total:
{provide, useClass}— a class provider{provide, useFactory}— a factory provider{provide, useValue}— a value provider
Dependent providers?: Array<Function | IProvider> inside of provider (class and factory) are extra dependencies that are created before provider and delivered as dependencies to provider itself.
interface IProvider {
provide: any;
useValue?: any;
useClass?: Function;
useFactory?: Function;
providers?: Array<Function | IProvider>;
}
Injector API¶
Mutable providers
By default all providers are immutable, however you can define mutable provider keys. If provider is not mutable, and you are trying to create new instance of same provider on current Injector instance, injector will throw error.
Injector.getProviders(provider: IProvider, propertyKey?: string) will return all providers which needs to be injected, if propertyKey is not defined injector will return providers for constructor.
Injector.getAllMetadataForTarget(provider: IProvider) will return all metadata, injector cache them internally. Works with class provider only.
class Injector {
constructor(_parent?: Injector, keys?: Array<any>);
static getProviders(provider: IProvider, propertyKey?: string): Array<IProvider>;
// returns all metadata for provider
static getAllMetadataForTarget(provider: IProvider): Array<IMetadata>;
// creates new child injector, provider and providers
static createAndResolveChild(parent: Injector, Class: Function | IProvider, providers: Array<MixedProvider>): Promise<Injector>;
// creates new injector, provider and providers
static createAndResolve(Class: Function | IProvider, providers: Array<MixedProvider>): Promise<Injector>;
// creates new provider and providers
createAndResolve(provider: IProvider, providers: Array<IProvider>): Promise<any>;
// cleans current injectables and all child injectors & providers
destroy(): void;
// check if provider exists on current SyncInjector instance
has(key: any): boolean;
// get provider value from current SyncInjector if not found bubble parent's
// if not found on any of parents exception is thrown.
get(provider: string, Class?: IProvider): any;
get<T>(provider: Type<T>, Class?: IProvider): T;
// set provider and value
set(key: any, value: Object): void;
getParent(): Injector;
setParent(injector: Injector): void;
setName(provider: IProvider): void;
hasChild(injector: Injector): boolean;
addChild(injector: Injector): this;
}
Sync Injector API¶
Since version 8.x default Injector behavior is converted to async API, if you want to use sync api you need to use Injector.Sync.createAndResolve or Injector.Sync.createAndResolveChild difference is that Async API supports Async providers, it's allowed to use of async/await in factory and return Promises in value provider!
class SyncInjector {
constructor(_parent?: Injector, keys?: Array<any>);
static getProviders(provider: IProvider, propertyKey?: string): Array<IProvider>;
// returns all metadata for provider
static getAllMetadataForTarget(provider: IProvider): Array<IMetadata>;
// creates new child injector, provider and providers
static createAndResolveChild(parent: Injector, Class: Function | IProvider, providers: Array<MixedProvider>): Injector;
// creates new injector, provider and providers
static createAndResolve(Class: Function | IProvider, providers: Array<MixedProvider>): Injector;
// creates new provider and providers
createAndResolve(provider: IProvider, providers: Array<IProvider>): any;
// cleans current injectables and all child injectors & providers
destroy(): void;
// check if provider exists on current SyncInjector instance
has(key: any): boolean;
// get provider value from current SyncInjector if not found bubble parent's
// if not found on any of parents exception is thrown.
get(provider: string, Class?: IProvider): any;
get<T>(provider: Type<T>, Class?: IProvider): T;
// set provider and value
set(key: any, value: Object): void;
getParent(): Injector;
setParent(injector: Injector): void;
setName(provider: IProvider): void;
hasChild(injector: Injector): boolean;
addChild(injector: Injector): this;
removeChild(injector: Injector): boolean;
}
Injector scopes¶
An injector holds providers and can have one parent and many children. get() looks at the current injector first and then walks up the parent chain; has() only checks the current injector.
const root = new SyncInjector();
root.set("TOKEN", "value");
const child = new SyncInjector(root);
root.addChild(child);
child.get("TOKEN"); // "value", resolved through the parent
child.has("TOKEN"); // false, has() is local only
Rules worth knowing:
new Injector(parent)does not register the child. The parent pointer is set, but the child is not inparent.getChildren(). Callparent.addChild(child)for that, otherwisechild.destroy()cannot detach it.addChildis idempotent and refuses to move a child that already has a different parent.removeChild(child)detaches a registered child, preserving the order of the remaining children, and returnsfalsewhen the child was never registered.detach()delegates to it, so detaching an unregistered child no longer removes an unrelated sibling.destroy()detaches, clears providers and clears children. Anything still resolving after that throws.
Metadata caching¶
getProviders resolves constructor parameters once per class and caches the result:
- The cache is a
WeakMapkeyed byuseClass, so dynamically created classes stay collectable. It used to be a strongMapkeyed byprovide, which retained every class ever seen. - Entries are validated against
getMetadataVersion()from@typeix/metadata, so a decorator applied after the first resolution is honoured instead of served stale. design:paramtypesis never mutated. The array belongs to reflect-metadata and is shared with every other reader of the class (resty-ws,@typeix/resty-swagger,@typeix/resty-graphql). Resolution copies it before substituting inject tokens, so the declared types stay readable.- A provider without a class (
{provide: "TOKEN"},{provide: T, useValue: …}) resolves to an empty metadata list rather than throwing.
Performance notes¶
Measured on Node 26:
| cost | |
|---|---|
instantiating one class (new SyncInjector + createAndResolve + destroy) | ~2 µs |
verifyProvider | 0.0027 µs |
getProviders, cache hit | one WeakMap lookup |
| adding 1 000 children | ~0.3 ms total |
Injection is roughly 4% of an HTTP request in a resty application, so this is not a place to look for speedups.
Limitations¶
verifyProviderson a bare token produces{provide: undefined, useClass: undefined};createInstanceonly survives that through itsisDefined(item.provide)fallback. Prefer passing a fullIProviderwhen the token is not a class.- The parameter cache is per class, not per provider token, so two providers aliasing the same class share the cached parameter list.