【问题标题】:TSyringe: How to change a parameter of an injected object?TSyringe:如何更改注入对象的参数?
【发布时间】:2022-04-22 16:17:52
【问题描述】:

我有一个包含多个不同组件的应用程序,每个组件都有自己的依赖项,并且正在使用 TSyringe 来管理依赖项注入。其中一个组件是这样的运算符:

// myoperator.ts

@injectable()
export class MyOperator {
    constructor(
        private dependencyA: DependencyA,
        protected dependencyB: DependencyB,
        protected dependencyC: DependencyC,
        protected operationType: string
    ){
         // initialize operator, etc.
    }

    // ...

}

它是一个执行操作的类,依赖于一堆其他类,并且有一个字符串参数指定它将操作的方式。

在主应用程序中,我正在初始化主应用程序使用的所有不同组件,我需要使用几种不同的操作类型来初始化 MyOperator。

// mainapp.ts

@singleton()
export class MainApp {
    constructor(
        componentA: ComponentA,
        componentB: ComponentB,
        componentC: ComponentC,
        operatorWithOperationTypeFoo: MyOperator // the operationType should be "foo"
        operatorWithOperationTypeBar: MyOperator // the operationType should be "bar"
        operatorWithOperationTypeBaz: MyOperator // the operationType should be "baz"
    ) {
         // initialize main app, etc.        
    }

    public start() {
        // start main app etc.
    
    }
}

// main.ts

const app = container.resolve(MainApp);
app.start();

我的问题是,在 MainApp 构造函数参数中定义 MyOperator 类中的单个 operationType 参数时,如何更改它们?

【问题讨论】:

  • 当被告知:“更改 MyOperator 类中的 operationType 参数”时,您到底是什么意思?这是一个受保护的参数,您不能在外部实例中更改它(只能从实例内部的方法)。对于注入原始值,请使用 github.com/microsoft/…
  • @ДенищукПавлоМиколайович 我的意思是在初始化时更改它。我有一个 MyOperator 类,我需要每个初始化实例的 operationType 都不同。

标签: typescript dependency-injection tsyringe


【解决方案1】:

我最终意识到解决方案非常简单:继承。

我声明我的基本运算符:

@singleton()
export class MyOperator {
    constructor(
        private dependencyA: DependencyA,
        protected dependencyB: DependencyB,
        protected dependencyC: DependencyC,
        protected operationType: string
    ){
         // initialize operator, etc.
    }

    // ...

}

然后我从这个运算符扩展我的其他运算符,注入依赖项:

container.register(CustomType.BAZ, { useValue: CustomType.BAZ });


@singleton()
export class MyOperatorWithOperationTypeBaz extends MyOperator {
    constructor(
        private dependencyA: DependencyA,
        protected dependencyB: DependencyB,
        protected dependencyC: DependencyC,
        @inject(CustomType.BAZ) protected operationType: string
    ){
         super()
         // initialize operator, etc.
    }

    // ...

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-19
    • 2013-08-30
    • 2021-01-09
    • 2015-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多