使用tsyringe的Typescript动态依赖项注入



我正在尝试构建和示例以了解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);
}
}

总计

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);
}
}

index.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 = ???

有没有办法让我有两个不同行为的计算器,或者我做得完全错了?

由于OperationSub不在任何地方使用,因此它不会影响注入的Operation值。

具有不同依赖集的计算器应该用多个容器表示。求和计算器可以被视为默认实现并使用根容器,或者两个实现都可以由子容器表示,而根容器保持抽象。

// common deps are registered on `container`
const sumContainer = container.createChildContainer();
const subContainer = container.createChildContainer();
sumContainer.register("Operation", { useClass: Sum });  
subContainer.register("Operation", { useClass: Sub });
const calculatorSum = sumContainer.resolve(Calculator);
const calculatorSub = subContainer.resolve(Calculator);

相关内容

  • 没有找到相关文章

最新更新