Skip to content

ioc

Description

Inversion of Control.

Inversion of control is a very versatile tool that helps you manage dependency injection.

One of the great advantages of @dreamkit/ioc is that it does not use decorators, is fully typed, and allows you to manually inject dependencies for testing purposes.

DreamKit uses it extensively and hands over part of its management to the user, allowing the user to consume only the dependencies they need and/or create their own dependencies.

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 { $route, context, IocClass } from "dreamkit";
abstract class ThirdModel {
abstract fetch(): string;
}
class MyModel extends IocClass({ ThirdModel }) {
fetch() {
return this.thirdModel.fetch();
}
}
export default $route.path("/").create(() => {
class ThirdModelImpl extends ThirdModel {
override fetch() {
return "resolved";
}
}
const manualModel = new MyModel({ thirdModel: new ThirdModelImpl() });
const autoModel = context
.fork()
.register(ThirdModel, { value: new ThirdModelImpl() })
.resolve(MyModel);
return (
<>
<p>{manualModel.fetch()}</p>
<p>{autoModel.fetch()}</p>
</>
);
});

Optional parameter

import { context, IocClass, iocParam, ServiceClass } from "dreamkit";
class StringModel {
toUpperCase(value: string) {
return value.toUpperCase();
}
}
class MyModel extends IocClass({
string: iocParam(StringModel).optional(),
}) {
toUpperCase(value: string) {
return this.string?.toUpperCase(value);
}
}
export class MyService extends ServiceClass({}) {
onStart() {
const model1 = new MyModel({});
const model2 = new MyModel({
string: {
toUpperCase(value) {
return value.toUpperCase();
},
},
});
const model3 = context
.fork()
.register(StringModel, { useFactory: () => new StringModel() })
.resolve(MyModel);
console.log({
model1: model1.toUpperCase("text"), // undefined
model2: model2.toUpperCase("text"), // "TEXT"
model3: model3.toUpperCase("text"), // "TEXT"
});
}
}