使用通用接口时,SimpleInjector会注入一个空集合

时间:2018-12-23 16:19:17

标签: c# dependency-injection simple-injector

我正在尝试在简单注入器docs中实现类似的情况CompositeValidator

这是复合类:

public class CompositePriceCalculator<T> : IPriceCalculator<T>
{
    private readonly IEnumerable<IPriceCalculator<T>> _priceCalculators;

    public CompositePriceCalculator(IEnumerable<IPriceCalculator<T>> priceCalculators)
    {
        this._priceCalculators = priceCalculators;
    }

    public double CalculatePrice(T item)
    {
       var totalPrice = _priceCalculators.Sum(priceCalc => priceCalc.CalculatePrice(item));
       return totalPrice;
    }
}

IPriceCalculator的某些实现:

public class Class1 : IPriceCalculator<SomeModel>
{
    public double CalculatePrice(SomeModel item) => ...
}

注册:

container.Collection.Register(typeof(IPriceCalculator<>), new [] { typeof(Class1) });
container.Register(typeof(IPriceCalculator<>), typeof(CompositePriceCalculator<>),
                Lifestyle.Scoped);

由于某种原因,在CalculatePrice类中输入CompositePriceCalculator方法时-_priceCalculators集合为空(计数= 0)。

有人可以协助为什么Class1不注入IEnumerable<IPriceCalculator<T>>集合吗?

更新

假设SomeModelBaseModel继承

public class SomeModel : BaseModel
{
}

Class1实现IPriceCalculator<BaseModel>,但需要SomeModel来实现。

public class Class1 : IPriceCalculator<BaseModel>
{
    public double CalculatePrice(BaseModel item)
    {
        var someModel = item as SomeModel;
        // Uses someModel
    }
}

任何要CalculatePrice的类都以IPriceCalculator实现BaseModel,以便CompositePriceCalculator迭代所有这些IPriceCalculator<BaseModel>实例。

public class Class2 : IPriceCalculator<BaseModel>
{
    public double CalculatePrice(BaseModel item)
    {
        var someModel2 = item as SomeModel2;
        // Uses someModel2
    }
}

总有办法以避免在SomeModel中强制转换为Class1的方式设计代码,但仍然在所有IPriceCalculator上获得迭代吗?

0 个答案:

没有答案