UNPKG

reactant-di

Version:

A dependency injection lib for Reactant

69 lines (66 loc) 1.92 kB
import 'reflect-metadata'; import { LazyServiceIdentifer, decorate, inject as inject$1 } from 'inversify'; import { METADATA_KEY } from '../constants.js'; import { lookupServiceIdentifier } from '../util.js'; import { forwardRef } from '../forwardRef.js'; /** * ## Description * * You can use `@inject()` to perform the required dependency injection module to decorate in the constructor of an injectable class. * * If the default is a dependency injection of the class itself as a type, e.g. `@inject(Foo) foo: Foo`, then it is exactly the same as `foo: Foo`. * * ## Example * * ```ts * @injectable() * class Bar { * getValue() { * return 'bar'; * } * } * * @injectable() * class Foo { * getValue() { * return 'foo'; * } * } * * @injectable() * class FooBar { * constructor(@inject() public bar: Bar, @inject('foo') public foo: Foo) {} * } * * const fooBar = testBed({ * modules: [ * Bar, * { provide: 'foo', useClass: Foo }, * ], * main: FooBar, * }); * * expect(fooBar.instance.foo.getValue()).toBe('foo'); * ``` */ function inject(serviceIdentifierOrFunc) { return function (target, key, index) { var self = Reflect.getMetadata(METADATA_KEY.paramtypes, target)[index]; var serviceIdentifier; if (serviceIdentifierOrFunc instanceof LazyServiceIdentifer) { serviceIdentifier = serviceIdentifierOrFunc; } else if (typeof serviceIdentifierOrFunc === 'undefined') { serviceIdentifier = forwardRef(function () { return lookupServiceIdentifier(target, self, index); }); } else { serviceIdentifier = forwardRef(function () { return lookupServiceIdentifier(target, serviceIdentifierOrFunc, index); }); } decorate(inject$1(serviceIdentifier), target, index); }; } export { inject };