文档
层次依赖注入系统

层次依赖注入系统

在大型项目中,一个注入器能做的事情较为有限,redi 允许你在多个注入器之间构建父子关系以形成层次依赖注入系统。

父子关系的创建

在两个注入器之间建立父子关系有两种方法,第一种是通过父注入器的 createChild 方法:

const parentInjector = new Injector([[PlatformService]])
const childInjector = parentInjector.createChild([[OrderService]]) // 传入子注入器的绑定

第二种是创建子注入器时将父注入器传递进去:

const parentInjector = new Injector([[PlatformService]])
const childInjector = new Injector([[OrderService]], parentInjector)

单向依赖查找

当子注入器无法解析标识符时,它将会调用其父注入器进行解析,如果父注入器不存在且该标识符对应的依赖是必须的才会抛出错误。下面的例子中,PlatformService 将会由 parentInjector 创建:

childInjector.get(PlatformService)

依赖查找控制

你可以控制依赖查找的过程,可以通过 SkipSelf 来跳过当前注入器,通过 Self 将查找过程限制在当前注入器。

class ChartComponent {
  constructor(
    @Self() @Inject(Container) private readonly selfContainer: Container,
    @SkipSelf() @Optional(Container) private readonly parentContainer?: Container
  ) {}
}

SkipSelfSelf 同样可以用于工厂函数:

const dependencies = [
  [Container],
  [IChartComponent, {
    useFactory: (parentContainer: Container, selfContainer: Container) => {
      // ...
    },
    deps: [
      [new SkipSelf(), Container],
      [new Self(), Container],
    ]
  }]
]