我有三个类的相对简单的设置。我正在使用inversify进行依赖项注入。但是,当将类MessageBroker注入派生类Repository中时,MessageBroker是未定义的:

import 'reflect-metadata';
import { injectable, inject, Container, unmanaged } from 'inversify';

const container = new Container();

const registerProviders = (...providers: any[]) =>
  providers.forEach(provider => container.bind(provider.name).to(provider));

const getProvider = (provider): any => container.get(provider.name);

@injectable()
export class MessageBroker {
  start = () => console.log('init message broker');
}

@injectable()
export abstract class Repository {
  @inject(MessageBroker.name) private mb: MessageBroker;

  constructor(@unmanaged() protected readonly user: any) {}

  // this.mb is undefined
  initialize = () => this.mb.start();
}

@injectable()
export class UserRepository extends Repository {
  constructor() {
    super({ user: 'some object' });
    this.initialize();
  }
}

registerProviders(UserRepository, Repository, MessageBroker);

const repo: UserRepository = getProvider(UserRepository);


您可以自己尝试。我创建了一个小的GitHub存储库:https://github.com/flolude/stackoverflow-inversify-injected-service-undefined

运行脚本时,出现以下错误:

/project/index.ts:22
  initialize = () => this.mb.start();
                             ^
TypeError: Cannot read property 'start' of undefined
    at UserRepository.Repository.initialize (/project/index.ts:22:30)
    at new UserRepository (/project/index.ts:29:10)
    at _createInstance (/project/node_modules/inversify/lib/resolution/instantiation.js:21:12)
    at Object.resolveInstance (/project/node_modules/inversify/lib/resolution/instantiation.js:41:18)
    at /project/node_modules/inversify/lib/resolution/resolver.js:72:42
    at Object.resolve (/project/node_modules/inversify/lib/resolution/resolver.js:96:12)
    at /project/node_modules/inversify/lib/container/container.js:319:37
    at Container._get (/project/node_modules/inversify/lib/container/container.js:310:44)
    at Container.get (/project/node_modules/inversify/lib/container/container.js:230:21)
    at getProvider (/project/index.ts:9:50)


附言将代码编译为Javascript时,我得到几乎相同的错误

最佳答案

您的MessageBroker仅在内存中设置,但从未实例化,这就是如何获取未定义的错误。在您的构造函数中,您需要设置

this.mb = new MessageBroker();

无需上述行即可完成此操作的另一种方法是将一个空参数签名的构造函数添加到MessageBroker类中。

09-25 15:46