我有一个包含多个不同组件的应用程序,每个组件都有自己的依赖项,并且正在使用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();我的问题是,当在operationType构造函数参数中定义单个MyOperator参数时,如何更改MainApp类中的单个MainApp参数?
发布于 2022-04-22 08:17:52
我最终意识到解决方案非常简单:继承。
我宣布我的基本操作员:
@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.
}
// ...
}https://stackoverflow.com/questions/70595458
复制相似问题