本文介绍了城堡温莎:如何将所有接口的实现注入到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 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:

Direct link to Castle Resolvers: Resolvers.

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

10-10 20:49