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?
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);
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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With