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 开发者_Go百科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>>>());
精彩评论