c# - 温莎城堡 : How do I inject all implementations of interface into a ctor?

标签 c# dependency-injection castle-windsor

我编写了一个由多个类实现的接口(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/

相关文章:

c# - ASP.Net MVC 模型 : MinLength Limit only in StringLength validation

C# ConcurrentDictionary 与线程控制的 ManualResetEvent

java - 通过 XML 或代码的 JSF Spring 注入(inject)

caSTLe-windsor - CaSTLe 温莎生活方式问题

c# - CaSTLe Windsor - 一个实现多个接口(interface)的类

c# - Xamarin.Forms - XAML 中 <div> 的对应物?

c# - 何时需要dispose()的规则是什么?

c# - 枚举类模式是否与 DI 不兼容?

java - Spring Java 对象依赖注入(inject)

c# - CaSTLe Windsor 多种生活方式( hibernate )