【问题标题】:How to inject list of base interfaces to class如何将基接口列表注入类
【发布时间】:2018-08-09 09:21:44
【问题描述】:

我有一个程序,其中有一些带有自定义接口的服务,但它们都继承自 IService。这些服务在 Simple Injector 容器中使用它们的自定义接口注册为单例,但在一个主类中,我希望它们都使用IEnumerable<IService> 注入到构造函数中。这不起作用,因为IEnumerable<IService> 未注册。我的问题是如何配置容器以允许在构造函数中检索它们——我可以手动解析类型,但我应该避免这种反模式。

// sample service (one of many)    
public interface IHttpServerService : IService
...
_container.RegisterSingleton<IHttpServerService, HttpServerService>();
...
public Controller(IEnumerable<IService> services)
...

【问题讨论】:

  • 你能给我们看一些代码吗?
  • 我添加了一些伪代码——idead是基本的所以没有太多代码

标签: c# dependency-injection simple-injector


【解决方案1】:

只需添加:

container.RegisterSingleton<IHttpServerService, HttpServerService>();

container.Collection.Register<IService>(
    typeof(IHttpServerService),
    // more implementations here
);

【讨论】:

  • 感谢您这么快的回答。不幸的是,现在我有:IHttpServerService (Singleton) 的注册映射到与 IService (Transient) 的注册相同的实现 (HttpServerService)
  • 您的更新正在运行 - 抱歉延迟。我不得不承认,在 stackoverflow 上观看你的活动会让你放弃某种改写 :)
  • 我更新了我的答案。这种行为不是错误,而是“设计使然”。见this
猜你喜欢
  • 1970-01-01
  • 2020-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-20
  • 2011-11-29
相关资源
最近更新 更多