gpt4 book ai didi

c# - 温莎城堡 : inject IEnumerable using only a subset of registered components for IService

转载 作者:太空狗 更新时间:2023-10-29 23:05:00 28 4
gpt4 key购买 nike

考虑示例 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...
}
}

让我们想象在组合根中进行以下注册:

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

这种场景效果很好,我做了几次。

如果出于某种原因,我想在 Consumer 类的构造函数中只注入(inject) IService 的两个不同实现,例如只注入(inject) FooService 和 BarService (< strong>同时继续在 AnotherConsumer 的构造函数中注入(inject) IService 的所有可用实现)?

有没有一种优雅的方式来做到这一点?

最佳答案

我捕获了 the first edition 的副本的 Dependency Injection Principles, Practices, and Patterns .它包含一个关于温莎城堡的完整章节,并讨论了这个确切的场景。诀窍是做两件事:

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

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

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

关于c# - 温莎城堡 : inject IEnumerable<IService> using only a subset of registered components for IService,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52702131/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com