我正在尝试在简单注入器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>>
集合吗?
更新
假设SomeModel
从BaseModel
继承
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上获得迭代吗?