2014-06-23 36 views
9

考慮所有註冊對象的列表。得到以下</p> <pre><code>builder.Register(c => new A()); builder.Register(c => new B()); builder.Register(c => new C()); </code></pre> <p><code>B</code>和<code>C</code>都<code>ISomeInterface</code>實現某個接口

我現在想得到一個IEnumerable所有註冊對象,實現ISomeInterface

如何在Autofac中完成此操作?

+0

Autofac不真正支持你正在問的問題。如果您無法更改註冊,您可能會被洗劫一空。對註冊集合進行任何查詢都不一定會考慮動態註冊來源(其中一些自動註冊在容器中 - 以支持諸如「IEnumerable '等)。您從查詢中得到的內容可能不是完整的列表。 –

回答

12

只是嘗試這樣做,工作和不依賴於生命週期方面:使用激活,而不是

var types = con.ComponentRegistry.Registrations.Where(r => typeof(ISomeInterface).IsAssignableFrom(r.Activator.LimitType)).Select(r => r.Activator.LimitType); 

然後解決

枚舉類型:

IEnumerable<ISomeInterface> lst = types.Select(t => con.Resolve(t) as ISomeInterface); 
+0

不錯。比我的實施更清潔。 – kasperhj

19

如果你有

container.Register(c => new A()).As<ISomeInterface>(); 
container.Register(c => new B()).As<ISomeInterface>(); 

然後當你做

var classes = container.Resolve<IEnumerable<ISomeInterface>>(); 

你會得到一個變量,它是ISomeInterface的列表,包含A和B

+0

這不起作用。這些組件沒有註冊爲「ISomeInterface」,但實現它們不會那麼少。 – kasperhj

+0

你不能這樣做:container.Register(c => new SomeClassA())。作爲()? –

+0

不幸的是,沒有。實際註冊不在我的控制之下。 – kasperhj

2

這是我如何做它。

var l = Container.ComponentRegistry.Registrations 
      .SelectMany(x => x.Services) 
      .OfType<IServiceWithType>() 
      .Where(x => 
       x.ServiceType.GetInterface(typeof(ISomeInterface).Name) != null) 
      .Select(c => (ISomeInterface) c.ServiceType); 
+0

這對我不起作用 - 在'Select'子句中出現'System.InvalidCastException:'失敗:'無法投射類型爲'System.RuntimeType'的對象以鍵入'MyCompany.Communications。 Core.ICommunicationService '''。 – Tagc

相關問題