Typescript Inversifyjs:将容器传递给另一个对象会导致绑定解析失败
我有以下资料:Typescript Inversifyjs:将容器传递给另一个对象会导致绑定解析失败,typescript,dependency-injection,inversifyjs,Typescript,Dependency Injection,Inversifyjs,我有以下资料: //Editor.TS let values = await Promise.all([Theme.getTheme(config.theme), I18n.getI18n(config.i18n)]); //Set up DI container this.services = new Container(); decorate(injectable(), EventEmitter); this.services.bind<IContext>(TYPES.Cont
//Editor.TS
let values = await Promise.all([Theme.getTheme(config.theme), I18n.getI18n(config.i18n)]);
//Set up DI container
this.services = new Container();
decorate(injectable(), EventEmitter);
this.services.bind<IContext>(TYPES.Context).toConstantValue(this);
this.services.bind<Theme>(TYPES.Theme).toConstantValue(values[0]);
this.services.bind<I18n>(TYPES.I18n).toConstantValue(values[1]);
this.services.bind<any>(TYPES.Data).toConstantValue(data);
this.services.bind<Toolbox>(TYPES.Toolbox).to(Toolbox).inSingletonScope();
this.services.bind<Workspace>(TYPES.Workspace).to(Workspace).inSingletonScope();
这里,插件
参数可以是构造函数
或[构造函数,配置:任意]
所以问题是,当插件的构造函数运行时,我得到以下错误:
未捕获(承诺中)错误:找不到的匹配绑定
服务标识符:符号(I18n)
请记住,对get
的完全相同的调用,仅在定义为容器的相同函数中才能正常工作
如果我调试并中断this.i18n=services.get(TYPES.i18n)代码>在APlugin.ts中,我看到:
因此,看起来容器
已正确设置并正常工作,\u bindingDictionary
属性包含对类型的引用。I18n
。我还应该提到,所有绑定都会出现这个问题。用任何其他绑定类型替换get
,会产生相同的错误
我做了一些挖掘,似乎故障点在getBindings
函数中:
调用bindingDictionary.hasKey
失败,即使结果应该是true
原因是每次调用Symbol(…)
都会创建一个唯一的符号,而不管参数是否相同
关键是使用Symbol.for(..)
。这将创建一个符号并将其存储在全局符号缓存中,如果该符号已经存在,则返回该符号。这将在不同的环境下继续存在
//APlugin.ts
constructor(config, services: Container) {
this.currentLang = this.defaultLang = config.defaultLanguage;
this.supportedLangs = config.supportedLanguages;
this.i18n = services.get<I18n>(TYPES.I18n);
this.context = services.get<IContext>(TYPES.Context);
//Editor Events
this.context.on("dataGenerating", e => this.onDataGenerating());
this.context.on("dataGenerated", data => this.onDataGenerated(data));
}
//Editor.ts
loadPlugin(plugin): IEditorPlugin {
let instance;
if (Array.isArray(plugin))
instance = new plugin[0](plugin[1], this.services);
else
instance = new plugin[0](this.services);
this.plugins.push(instance);
if (typeof instance.getMenuDom === 'function')
this.workspace.addButton(instance.getMenuDom());
return instance;
}