我使用 Simple Injector 作为我的 IoC 容器。我已经为单个通用接口开发了许多(请原谅我可能使用了错误的术语)部分封闭的实现。
我希望能够请求通用接口,并根据提供的类型,让 Simple Injector 返回正确的类实现。(我可以理解这可能是一个禁忌,因为如果做错了实现可能会重叠等,但我仍然想知道它是否可以完成。)
根据下面的代码片段,如何配置 Simple Injector 以返回一个实例ITrim<Ford, Green>
?
通用基类层:
public interface IColour { }
public interface IVehicle { }
public interface ITrim<TVehicle, TColour>
where TVehicle : IVehicle
where TColour : IColour
{
void Trim(TVehicle vehicle, TColour colour);
}
public abstract class TrimVehicle<TVehicle, TColour> : ITrim<TVehicle, TColour>
where TVehicle : IVehicle
where TColour : IColour
{
public virtual void Trim(TVehicle vehicle, TColour colour) { }
}
中间层,为某类车辆提供通用代码:
public abstract class Green : IColour { }
public abstract class Blue : IColour { }
public abstract class Car : IVehicle { }
public abstract class Bike : IVehicle { }
public abstract class TrimCar<TCar, TColour> : TrimVehicle<TCar, TColour>
where TCar : Car
where TColour : IColour
{
public override void Trim(TVehicle vehicle, TColour colour)
{
base.Trim(vehicle, colour);
}
}
public abstract class TrimBike<TBike, TColour> : TrimVehicle<TBike, TColour>
where TBike : Bike
where TColour : IColour
{
public override void Trim(TVehicle vehicle, TColour colour)
{
base.Trim(vehicle, colour);
}
}
最后一层,提供更具体的实现:
public class Ford : Car { }
public class TrimFord<TFord, TColour> : TrimCar<TFord, TColour>
where TFord : Ford
where TColour : IColour
{
public override void Trim(TVehicle vehicle, TColour colour)
{
base.Trim(vehicle, colour);
}
}
public class Yamaha : Bike { }
public class TrimYamaha<TYamaha, TColour> : TrimBike<TYamaha, TColour>
where TYamaha : Yamaha
where TColour : IColour
{
public override void Trim(TVehicle vehicle, TColour colour)
{
base.Trim(vehicle, colour);
}
}