7

I need to get, from an IComponentContext, a list of registered Type's that implement a particular interface.

I don't want actual instances of the types, but rather a list of Type of which I could get instances.

I want to use this list to generate subscriptions on a message bus.

How do I get all registered implementations of an interface in Autofac?

George Stocker
  • 57,289
  • 29
  • 176
  • 237
David Pfeffer
  • 38,869
  • 30
  • 127
  • 202
  • 1
    Have you tried to use Reflection to iterate through all types within an assembly and check if they implement `IComponentContext`? See [Getting all types that implement an interface with C# 3.5](http://stackoverflow.com/questions/26733/getting-all-types-that-implement-an-interface-with-c-sharp-3-5) – Nick Hill Dec 27 '12 at 21:32
  • 1
    @NikolayKhil That's not the question. I need to look through the context and find registered types. This is an Autofac-specific question. – David Pfeffer Dec 27 '12 at 21:54

2 Answers2

14

I figured this out --

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);
David Pfeffer
  • 38,869
  • 30
  • 127
  • 202
2

With AutoFac 3.5.2 (based on this article: http://bendetat.com/autofac-get-registration-types.html)

first implement this function:

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

then assume we you have builder,

var container = builder.Build();
using (var scope = container.BeginLifetimeScope())
{
   var types = GetImplementingTypes<T>(scope);
}
Mahmoud Moravej
  • 8,705
  • 6
  • 46
  • 65