【问题标题】:How to pass values in constructor using sigleton() in typescript?如何在打字稿中使用 singleton() 在构造函数中传递值?
【发布时间】:2020-03-14 12:38:52
【问题描述】:

我对如何在 typescript 中使用单例类在构造函数中传递值存有疑问。

我的代码.ts

import {singleton} from "tsyringe";

@singleton()
class Foo {
  constructor(data:string) 
{
this.data = data
}
}

// some other file
import "reflect-metadata";
import {container} from "tsyringe";
import {Foo} from "./foo";

const instance = container.resolve(Foo);

如何使用容器.resolve函数在构造函数中传递一个值。任何人都给出了如何传递值的示例代码。

【问题讨论】:

    标签: typescript typescript-typings typescript2.0 typescript-generics typescript1.5


    【解决方案1】:

    您可以执行以下操作将值注入构造函数:

    import {singleton} from "tsyringe";
    
    @singleton()
    class Foo {
      private str: string;
      constructor(@inject("SomeName") value: string) {
        this.str = value;
      }
    }
    
    // some other file
    import "reflect-metadata";
    import {container} from "tsyringe";
    import {Foo} from "./foo";
    
    const str = "test";
    
    container.register("SomeName", { useValue: str });
    const instance = container.resolve(Foo);
    

    【讨论】:

    • 如果 Foo 不是单例并且您想为每个实例的构造函数提供不同的参数,您将如何进行?
    【解决方案2】:

    @user1762087 要回答您的问题,如果您想为每个实例的构造函数提供不同的参数,您可以执行类似的操作

    import "reflect-metadata";
    import {container} from "tsyringe";
    import {Foo} from "./foo";
    
    const str = "test";
    
    container.registerInstance("SomeName", { useValue: str });
    const instance = container.resolve(Foo);
    
    // to clear up instances you've registered with registerInstance()
    container.clearInstances();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-14
      • 1970-01-01
      • 1970-01-01
      • 2019-12-12
      • 1970-01-01
      相关资源
      最近更新 更多