我正在尝试构建和示例以了解 DI 框架/库的工作原理,但我遇到了一些问题。
我有这个接口有两种可能的实现:
export interface Operation {
calculate(a: number, b: number): number;
}
子类
import { Operation } from "./operation.interface";
export class Sub implements Operation {
calculate(a: number, b: number): number {
return Math.abs(a - b);
}
}
sum.ts
import { Operation } from "./operation.interface";
export class Sum implements Operation {
calculate(a: number, b: number): number {
return a + b;
}
}
计算器.ts
import { Operation } from "./operation.interface";
import {injectable, inject} from "tsyringe";
@injectable()
export class Calculator {
constructor(@inject("Operation") private operation?: Operation){}
operate(a: number, b: number): number {
return this.operation.calculate(a, b);
}
}
索引.ts
import "reflect-metadata";
import { container } from "tsyringe";
import { Calculator } from "./classes/calculator";
import { Sub } from "./classes/sub";
import { Sum } from "./classes/sum";
container.register("Operation", {
useClass: Sum
});
container.register("OperationSub", {
useClass: Sub
});
const calculatorSum = container.resolve(Calculator);
const result = calculatorSum.operate(4,6);
console.log(result);
// const calculatorSub = ???
有没有办法让我有两个具有不同行为的计算器,或者我做错了?