我需要从一个IComponentContext
中获取实现特定接口的已注册Type
列表。
我不想要类型的实际实例,而是一个Type
的列表,我可以在其中获取实例。
我想使用这个列表在消息总线上生成订阅。
如何在Autofac中获取所有已注册接口实现的实现?
我明白了——
var types = scope.ComponentRegistry.Registrations
.SelectMany(r => r.Services.OfType<IServiceWithType>(), (r, s) => new { r, s })
.Where(rs => rs.s.ServiceType.Implements<T>())
.Select(rs => rs.r.Activator.LimitType);
using Autofac;
using Autofac.Core;
using Autofac.Core.Activators.Reflection;
...
private static IEnumerable<Type> GetImplementingTypes<T>(ILifetimeScope scope)
{
//base on http://bendetat.com/autofac-get-registration-types.html article
return scope.ComponentRegistry
.RegistrationsFor(new TypedService(typeof(T)))
.Select(x => x.Activator)
.OfType<ReflectionActivator>()
.Select(x => x.LimitType);
}
builder
,var container = builder.Build();
using (var scope = container.BeginLifetimeScope())
{
var types = GetImplementingTypes<T>(scope);
}
IComponentContext
接口吗?请参阅 使用 C# 3.5 获取实现接口的所有类型。 - Nick Hill