我现在想得到一个IEnumerable
所有注册对象,实现ISomeInterface
。
如何在Autofac中完成此操作?
我现在想得到一个IEnumerable
所有注册对象,实现ISomeInterface
。
如何在Autofac中完成此操作?
只是尝试这样做,工作和不依赖于生命周期方面:使用激活,而不是
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);
不错。比我的实施更清洁。 – kasperhj
如果你有
container.Register(c => new A()).As<ISomeInterface>();
container.Register(c => new B()).As<ISomeInterface>();
然后当你做
var classes = container.Resolve<IEnumerable<ISomeInterface>>();
你会得到一个变量,它是ISomeInterface的列表,包含A和B
这是我如何做它。
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);
这对我不起作用 - 在'Select'子句中出现'System.InvalidCastException:'失败:'无法投射类型为'System.RuntimeType'的对象以键入'MyCompany.Communications。 Core.ICommunicationService '''。 – Tagc
Autofac不真正支持你正在问的问题。如果您无法更改注册,您可能会被洗劫一空。对注册集合进行任何查询都不一定会考虑动态注册来源(其中一些自动注册在容器中 - 以支持诸如“IEnumerable'等)。您从查询中得到的内容可能不是完整的列表。 –