如何使用 Injector 而不是单例来获取类的新实例

Rav*_*avi 3 dependency-injection angular

我的 angular 应用程序中有两个可注入的类

@Injectable()
class B {}

@Injectable()
class A {
  constructor(b:B) { }
}
Run Code Online (Sandbox Code Playgroud)

我希望 A 类为单例,B 类为瞬态

我开始知道我可以在 A 类中使用ReflectiveInjector.resolveAndCreate来获取 B 类的实例。有没有更好的方法来实现这一点?

Max*_*kyi 5

由于提供者的所有现有配方都创建了单例,甚至工厂,您可以创建自己的注入器,从组件注入器继承所有提供者并使用resolveAndInstantiate方法每次获取新实例:

import { Component, Inject, Injector, ReflectiveInjector } from '@angular/core';

class P {
}

const ps = [];

class C {
  constructor(@Inject(P) p) {
    ps.push(p);
  }
}

@Component({
  moduleId: module.id,
  selector: 'my-app',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.css']
})
export class AppComponent {
  name = 'Angular';

  constructor(injector: Injector) {
    const parent = ReflectiveInjector.resolveAndCreate([P], injector);
    const child = parent.resolveAndCreateChild([C]);
    const c1 = child.resolveAndInstantiate(C);
    const c2 = child.resolveAndInstantiate(C);
    console.log(c1 === c2); // false

    console.log(ps[0] === ps[1]); // true

  }
}
Run Code Online (Sandbox Code Playgroud)

这是演示

还要记住,ReflectiveInjector@5.xx 中已弃用,而且似乎在新的StaticInjector 中别无选择。我报告了一个关于那个的问题