TSyringe:如何更改注入对象的参数?

TSyringe: How to change a parameter of an injected object?

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

// myoperator.ts

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

    // ...

}

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

在主应用程序中,我正在初始化主应用程序使用的所有不同组件,我需要用几种不同的操作类型初始化 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 class 中的单个 operationType 参数?

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

我声明我的基本运算符:

@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.
    }

    // ...

}