【问题标题】:How to share the same dependency Injection Tree with tsrynge?如何与 tsrynge 共享相同的依赖注入树?
【发布时间】:2019-10-28 15:06:08
【问题描述】:

我希望每个子容器的每个类只有一个实例。

import "reflect-metadata";
import {injectable, container, singleton} from "tsyringe";

const count = {
    bar: 0,
    foo: 0,
    fao: 0
}

@injectable()
class Foo {
    constructor() {
        count.foo += 1;

    }

    public helloWorld() {
        console.log("helloworld")
    }
}

@injectable()
export class Bar {
    constructor(public myFoo: Foo) {
        count.bar += 1;
    }


}

@injectable()
export class FAO {
    constructor(public myFoo: Foo) {
        count.fao += 1;
    }
}

const create = () => {
    const childContainer = container.createChildContainer();
    const myBar = childContainer.resolve(FAO);
    const other = childContainer.resolve(Bar);
}

create();
create();

我想在我的 childcontainer 中有一个“singleton”。每个子容器只对所有类进行一次实例化。 @singleton 仅在全局容器中解析。

我该怎么做?

【问题讨论】:

    标签: typescript dependency-injection injectable


    【解决方案1】:

    子容器中有一个方法registerSingleton

    const childContainer= container.createChildContainer();
    childContainer.registerSingleton(Foo);
    
    childContainer.resolve(Bar)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-06
      • 1970-01-01
      • 2021-04-01
      • 2019-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-17
      相关资源
      最近更新 更多