Skip to content

每次注入都构建新实例

可以使用 WithNew 来做到每次都注入一个新的实例,仅当依赖项是个类或者工厂时才有意义。

当注入项是一个类时:

let c = 0
class A {
count = c++
}
class B {
constructor(@WithNew() @Inject(A) private readonly a: A) {}
get(): number {
return this.a.count
}
}
const j = new Injector([[A], [B]])
const b1 = j.createInstance(B)
const b2 = j.createInstance(B)
expect(b1.get()).toBe(0)
expect(b2.get()).toBe(1)
})

当注入项是一个工厂时:

let c = 0
const ICount = createIdentifier<number>('ICount')
class B {
constructor(@WithNew() @Inject(ICount) public readonly count: number) {}
}
const j = new Injector([[B], [ICount, { useFactory: () => c++ }]])
const b1 = j.createInstance(B)
const b2 = j.createInstance(B)
expect(b1.count).toBe(0)
expect(b2.count).toBe(1)

注意此时 redi 不会缓存构造的实例,你需要自行调用依赖项的解构方法(例如 dispose)。