Skip to content

ioc

Description

Inversion of Control container.

Import

import {
context,
iocParam,
IocClass
} from "dreamkit";

Definition

declare const context: {
register(
key: any,
data: {
value?: any;
useClass?: any;
useFactory?: ($context: typeof context, key: any) => any;
singleton?: boolean;
},
): typeof context;
unregister(key: any): typeof context;
resolve(key: any): unknown;
fork(): typeof context;
};

Examples

Basic usage

import { context, IocClass, ServiceClass } from "dreamkit";
class Child extends IocClass({}) {
process(value: string) {
return value;
}
}
class CustomChild extends Child {
override process(value: string): string {
return value.toUpperCase();
}
}
class Parent extends IocClass({ Child }) {
process(value: string) {
return this.child.process(value);
}
}
export class TestService extends ServiceClass({ Parent }) {
onStart() {
const value0 = this.parent.process("hello");
const value1 = new Parent({ child: new Child() }).process("hello");
const value2 = context
.fork()
.register(Child, { useClass: CustomChild })
.resolve(Parent)
.process("world");
console.log([value0, value1, value2]); // ["hello", "WORLD"]
}
}

Optional

import { IocClass, iocParam, ServiceClass } from "dreamkit";
class Child extends IocClass({}) {
process(value: string) {
return value;
}
}
class Parent extends IocClass({ child: iocParam(Child).optional() }) {
process(value: string) {
return this.child?.process(value);
}
}
export class TestService extends ServiceClass({}) {
onStart() {
const value1 = new Parent({}).process("hello");
const value2 = new Parent({
child: {
process(value) {
return value.toUpperCase();
},
},
}).process("world");
console.log([value1, value2]); // [undefined, "WORLD"]
}
}