简体   繁体   中英

Autofac - Resolving IEnumerable Generic Interface at runtime

I found out how to resolve at runtime a generic interface using the below code. How would I resolve ALL instances of IGenericInterface<> to get back collection at runtime. I know in autofac we are supposed to use IEnumerable<T> but I don't know how to represent that in the below example:

 var typeInRuntime = typeof (SubClass1);
 var instance1 = container.Resolve(typeof(IGenericInterface<>)
                          .MakeGenericType(typeInRuntime));

This does not work obviously

 var typeInRuntime = typeof (SubClass1);
 var collection = container
                .Resolve(IEnumerable<typeof(IGenericInterface<>)
                .MakeGenericType(typeInRuntime)>);

You have to build the generic IEnumerable type in two steps. The following code works on my machine ;)

var t1 = typeof (IGenericInterface<>).MakeGenericType(typeof(SubClass1));
var t2 = typeof(IEnumerable<>).MakeGenericType(t1);
var collection = c.Resolve(t2);

Assert.That(collection, Is.InstanceOf<IEnumerable<IGenericInterface<SubClass1>>>());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM