城堡温莎:如何将所有接口的实现注入到ctor? [英] Castle Windsor: How do I inject all implementations of interface into a ctor?

查看:167
本文介绍了城堡温莎:如何将所有接口的实现注入到ctor?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个由多个类实现的接口。我想编写一个将所有注册实现注入其ctor的Service类。



我可以想到的唯一的解决方案是在ctor中调用服务定位器并请求Resolve()所有实现。



理想情况下,我想要这样的东西 -

  interface IVehicle 
{
void Start();
}

class Car:IVehicle
{
public void Start()
{
Console.WriteLine(Car started。 ;
}
}

class卡车:IVehicle
{
public void Start()
{
Console.WriteLine(卡车开始了。);
}
}

class摩托​​车:IVehicle
{
public void Start()
{
Console.WriteLine(摩托车开始了。);
}
}

class VehicleService
{
//如何注入IVehicle的所有实现?
public VehicleService(IEnumerable< IVehicle>车辆)
{
foreach(车辆中的车辆)
{
vehicle.Start();
}
}
}

strong> - 我应该提到我正在使用Castle Windsor。

解决方案

你必须使用 CollectionResolver 。检查此 Castle Windsor常见问题


Windsor,默认情况下,当您依赖于IFoo []时,
IEnumerable或IList将检查是否有一个组件
注册为该type(数组或IFoo的列表),如果
有注册为IFoo的组件(组件数组,不是
,与组件的数组相同),则不会。您可以更改
行为说当您看到数组或列表的IFoo只是给我所有
IFoos你可以得到你使用CollectionResolver。


直接链接到Castle Resolvers:解决方案


I've written an interface which is implemented by multiple classes. I want to write a Service class which will have all the registered implementations injected into its ctor.

The only solution I can think of is to call the Service Locator within the ctor and ask it to Resolve() all implementations.

Ideally I would like something like this -

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();
        }
    }
}

EDIT - I should mention I'm using Castle Windsor.

解决方案

You have to use CollectionResolver. Check this 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.

Direct link to Castle Resolvers: Resolvers.

这篇关于城堡温莎:如何将所有接口的实现注入到ctor?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆