gpt4 book ai didi

javascript - 无法将依赖项注入(inject)到派生类中

转载 作者:行者123 更新时间:2023-12-02 22:55:09 24 4
gpt4 key购买 nike

我有一个相对简单的设置,包含三个类。我正在使用 inversify 进行依赖注入(inject)。但是,当将类 MessageBroker 注入(inject)派生类 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 类中。

关于javascript - 无法将依赖项注入(inject)到派生类中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58016087/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com