@SkipSelf-decorator告诉DI从父注入器开始在整个树中查找依赖项
我在下面看到了@SkipSelf装饰器。在这种情况下,这个@SkipSelf
装饰器到底意味着什么?
class Dependency {}
@Injectable()
class NeedsDependency {
constructor(@SkipSelf() public dependency: Dependency) { this.dependency = dependency; }
}
const parent = ReflectiveInjector.resolveAndCreate([Dependency]);
const child = parent.resolveAndCreateChild([NeedsDependency]);
expect(child.get(NeedsDependency).dependency instanceof Dependency).toBe(true);
const inj = ReflectiveInjector.resolveAndCreate([Dependency, NeedsDependency]);
expect(() => inj.get(NeedsDependency)).toThrowError();
让我们逐行开始:
第一种情况:
A创建父注入器并将Dependency
添加到其中:
const parent = ReflectiveInjector.resolveAndCreate([Dependency]);
B创建子注入器并添加NeedsDependency
,由于Dependency
是在父注入器中提供的,因此DI框架可以解决NeedsDependency
的依赖关系(Dependency
(
const child = parent.resolveAndCreateChild([NeedsDependency]);
第二种情况:
A创建单个注入器并添加Dependency
&NeedsDependency
到它:
const inj = ReflectiveInjector.resolveAndCreate([Dependency, NeedsDependency]);
B这一次解析NeedsDependency
的依赖关系将失败,因为@SkipSelf()
应用于Dependency
,DI框架将忽略inj
注入器中的Dependency
实例,并尝试查找层次结构以找到一个不存在的满足此依赖关系的提供程序,因此inj.get(NeedsDependency)
将抛出一个错误,因为无法解析NeedsDependency
。
expect(() => inj.get(NeedsDependency)).toThrowError();