2014-06-23 31 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

相关问题