我编写了一个由多个类实现的接口(interface)。我想编写一个服务类,它将所有已注册的实现注入(inject)到它的构造函数中。
我能想到的唯一解决方案是在 ctor 中调用服务定位器并要求它 Resolve() 所有实现。
理想情况下我想要这样的东西-
interface IVehicle
{
void Start();
}
class Car : IVehicle
{
public void Start()
{
Console.WriteLine("Car started.");
}
}
class Truck : IVehicle
{
public void Start()
{
Console.WriteLine("Truck started.");
}
}
class Motorbike : IVehicle
{
public void Start()
{
Console.WriteLine("Motorbike started.");
}
}
class VehicleService
{
// How do I inject all implementations of IVehicle?
public VehicleService(IEnumerable<IVehicle> vehicles)
{
foreach (var vehicle in vehicles)
{
vehicle.Start();
}
}
}
编辑 - 我应该提到我正在使用 CaSTLe Windsor。
最佳答案
您必须使用 CollectionResolver
。检查这个Castle Windsor FAQ :
Windsor, by default when you have dependency on IFoo[], IEnumerable or IList will check if you have a component registered for that exact type (array or list of IFoo), not if you have any components registered for IFoo (array of components, is not the same as a component which is an array). You can change the behavior to say "When you see array or list of IFoo just give me all IFoos you can get" you use CollectionResolver.
城堡解析器的直接链接:Resolvers .
关于c# - 温莎城堡 : How do I inject all implementations of interface into a ctor?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10452155/