在Autofac中获取接口的所有注册实现

7

我需要从一个IComponentContext中获取实现特定接口的已注册Type列表。

我不想要类型的实际实例,而是一个Type的列表,我可以在其中获取实例。

我想使用这个列表在消息总线上生成订阅。

如何在Autofac中获取所有已注册接口实现的实现?


1
你尝试过使用反射来迭代程序集中的所有类型,并检查它们是否实现了 IComponentContext 接口吗?请参阅 使用 C# 3.5 获取实现接口的所有类型 - Nick Hill
1
@NikolayKhil 这不是问题所在。我需要查看上下文并找到已注册的类型。这是一个特定于Autofac的问题。 - David Pfeffer
2个回答

14

我明白了——

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);

1
ServiceType 没有实现 Implements 方法! - Mahmoud Moravej

2
使用AutoFac 3.5.2(根据此文章:http://bendetat.com/autofac-get-registration-types.html),首先实现此功能:
    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);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接