7

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

我不想要类型的实际实例,而是Type可以获得实例的列表。

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

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

4

2 回答 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);
于 2012-12-27T22:11:55.647 回答
2

使用AutoFac 3.5.2(基于这篇文章:http ://bendeat.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);
}
于 2015-04-14T04:22:10.293 回答