我已经实现了一个服务容器,它能够通过 reflect-metadata
解析它们来创建服务。用代码说话:
// The services
@Service()
export class Bar {
constructor() { console.log('i am bar'); }
}
@Service()
export class Foo {
constructor(bar: Bar) {}
}
// Creating an instance for Foo
Container.get<Foo>('foo');
这会导致 Foo 的解析实例带有正确注入(inject)的 Bar
实例。
但是当尝试检测循环依赖时,事情变得非常困惑:
@Service()
export class Foo {
constructor(b: Bar) {}
}
@Service()
export class Bar {
constructor(f: Foo) {}
}
Container.get<Foo>('foo'); // returns Foo, but not with an injected Bar instance
有趣的是 Reflect.getMetadata('design:paramtypes', target)
对于 Foo
返回 undefined
。一旦循环依赖项更改为非循环依赖项,就会再次返回正确的类型。
容器实现在这里可能无关紧要,但查看 Service
装饰器可能会很有趣:
export const Service = () : ClassDecorator => {
return (target: any): void => {
console.log(Reflect.getMetadata(DESIGN_PARAM_TYPES, target));
}
};
这会在依赖项变为循环时记录 undefined
,否则会正确返回所需的类型。
我的目标是对循环依赖抛出一个适当的异常——但我现在不可能检测到。为什么?以及如何解决这个问题?
最佳答案
目前的解决方法,因为我还没有找到解决办法:
注入(inject)服务时,我会检查 undefined
并抛出 ServiceResolvingFailedException
。不完全是我想要的,但至少可以通过某种方式告诉开发人员发生了什么。
关于typescript - 检测 TypeScript 中的循环依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48080152/