5

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

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

4

1 回答 1

6

由于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);
于 2020-10-13T11:59:05.493 回答