Castle Windsor:仅使用IService注册组件的子集注入IEnumerable <IService>

Enr*_*one 5 c# dependency-injection castle-windsor

请考虑示例C#控制台应用程序中的服务和组件的以下方案

public interface IService { }
public class FooService: IService { }
public class BarService: IService { }
public class BuzzService: IService { }
public class AwesomeService: IService { }

public class Consumer 
{
    public Consumer(IEnumerable<IService> services)
    {
        // do some initilization work here...
    }
}

public class AnotherConsumer 
{
    public AnotherConsumer(IEnumerable<IService> services)
    {
        // do some initilization work here...
    }
}
Run Code Online (Sandbox Code Playgroud)

让我们假设在组合根目录中进行以下注册:

var container = new WindsorContainer();

container.Kernel.Resolver.AddSubResolver(new CollectionResolver(container.Kernel, true));

container.Register(Component.For<IService>().ImplementedBy<FooService>());
container.Register(Component.For<IService>().ImplementedBy<BarService>());
container.Register(Component.For<IService>().ImplementedBy<BuzzService>());
container.Register(Component.For<IService>().ImplementedBy<AwesomeService>());

container.Register(Component.For<Consumer>());
container.Register(Component.For<AnotherConsumer>());

// consumer got injected all 4 different implementations of IService
// due to CollectionResolver
var consumer = container.Resolve<Consumer>();

// anotherConsumer got injected all 4 different implementations of 
// IService due to CollectionResolver
var anotherConsumer = container.Resolve<AnotherConsumer>(); 
Run Code Online (Sandbox Code Playgroud)

这种情况很好,我这样做了好几次.

如果由于某种原因,我想什么来注入Consumer类的构造函数中只有IService的两种不同的实现,例如仅FooService接口和BarService(同时仍继续注入AnotherConsumer的构造函数中IService的所有可用的实现)?

有一种优雅的方式吗?

Ste*_*ven 3

我拿起了《依赖注入原则、实践和模式》第一版的副本。它包含关于温莎城堡的完整章节并讨论了这个确切的场景。诀窍是做两件事:

  • 使用以下命令将集合注册定义为命名注册.Named(string)
  • Consumer指定要使用的覆盖.ServiceOverrides(object)

以下代码示例几乎直接来自书中(名称替换为您的示例):

container.Register(Component
    .For<IService>()
    .ImplementedBy<FooService>()
    .Named("Foo"));
container.Register(Component
    .For<IService>()
    .ImplementedBy<BarService>()
    .Named("Bar"));
container.Register(Component
    .For<IService>()
    .ImplementedBy<BuzzService>()
    .Named("Buzz"));
container.Register(Component
    .For<IService>()
    .ImplementedBy<AwesomeService>()
    .Named("Awesome"));

container.Register(Component
    .For<Consumer>()
    .ServiceOverrides(new
        {
            services = new[] { "Foo", "Bar" }
        }));

container.Register(Component.For<AnotherConsumer>());

var consumer = container.Resolve<Consumer>();
Run Code Online (Sandbox Code Playgroud)