我们在 Insersify JS 中已经有了 inSingletonScope。使用 .toConstantValue 的目的是什么?谁能告诉我我们什么时候想使用 .toConstantValue ?
如果您使用默认绑定:
container.bind<Katana>(Type.Katana).to(Katana);
每次出现
@Inject(Type.Katana)
时,Inversify 都会使用 Katana
创建 new
的新实例。
如果您使用
inSingletonScope
:
container.bind<Katana>(Type.Katana).to(Katana).inSingletonScope();
InversifyJS 将仅使用
new
并缓存创建的实例。所有后续 @Inject(Type.Katana)
将获得相同的实例。
然后您使用
toConstantValue
InversifyJS 永远不会使用 new
创建新实例,并且所有 @Inject(Type.Katana)
将获得相同的实例。当你声明绑定时,你就是调用 new
的人。
container.bind<Katana>("Katana").toConstantValue(new Katana());
在 InversifyJS 无法创建实例的情况下,使用
toConstantValue
非常有用。例如,当您无法注释要注入的类时。或者当您想要注入不是类且不使用 new
的内容时(例如 process.env.SOME_ENV_BAR
)。