Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a list of all registered objects implementing a certain interface

Tags:

autofac

Consider the following

builder.Register(c => new A());
builder.Register(c => new B());
builder.Register(c => new C());

B and C are both ISomeInterface.

I would now like to get an IEnumerable of all registered objects that implement ISomeInterface.

How can I accomplish this in Autofac?

like image 727
kasperhj Avatar asked Jun 23 '14 15:06

kasperhj


3 Answers

Just tried this, works and does not depend on lifetime context:

Enumerate types using Activator instead

var types = con.ComponentRegistry.Registrations
     .Where(r => typeof(ISomeInterface).IsAssignableFrom(r.Activator.LimitType))
     .Select(r => r.Activator.LimitType);

Then to resolve:

IEnumerable<ISomeInterface> lst = types.Select(t => con.Resolve(t) as ISomeInterface);
like image 69
mrvux Avatar answered Nov 07 '22 00:11

mrvux


If you have

container.Register(c => new A()).As<ISomeInterface>();
container.Register(c => new B()).As<ISomeInterface>();

Then when you do

var classes = container.Resolve<IEnumerable<ISomeInterface>>();

You will get a variable that is a list of ISomeInterface, containing A and B

like image 31
Tim Burkhart Avatar answered Nov 07 '22 00:11

Tim Burkhart


Here is how I did it.

var l = Container.ComponentRegistry.Registrations
          .SelectMany(x => x.Services)
          .OfType<IServiceWithType>()
          .Where(x => 
                 x.ServiceType.GetInterface(typeof(ISomeInterface).Name) != null)
          .Select(c => (ISomeInterface) c.ServiceType);
like image 5
kasperhj Avatar answered Nov 06 '22 22:11

kasperhj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!