Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all registered implementations of an interface in Autofac

Tags:

c#

autofac

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?

like image 931
David Pfeffer Avatar asked Dec 27 '12 21:12

David Pfeffer


People also ask

How do I get Autofac containers?

From Visual Studio, you can get it via NuGet. The package name is Autofac. Alternatively, the NuGet package can be downloaded from the GitHub repository (https://github.com/autofac/Autofac/releases).

What is resolve in Autofac?

After you have your components registered with appropriate services exposed, you can resolve services from the built container and child lifetime scopes. You do this using the Resolve() method: var builder = new ContainerBuilder(); builder. RegisterType<MyComponent>(). As<IService>(); var container = builder.

What is AsImplementedInterfaces?

RegistrationExtensions. AsImplementedInterfaces MethodSpecifies that a type from a scanned assembly is registered as providing all of its implemented interfaces.


1 Answers

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);
like image 148
David Pfeffer Avatar answered Sep 28 '22 14:09

David Pfeffer