[英]How to inject list of base interfaces to class
我有一個程序,其中有一些帶有自定義接口的服務,但它們都繼承自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)
...
只需添加:
container.RegisterSingleton<IHttpServerService, HttpServerService>();
container.Collection.Register<IService>(
typeof(IHttpServerService),
// more implementations here
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.