[英]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. 如何解析
IGenericInterface<>
所有实例以在运行时返回集合。 I know in autofac we are supposed to use IEnumerable<T>
but I don't know how to represent that in the below example: 我知道在autofac中我们应该使用
IEnumerable<T>
但我不知道如何在下面的例子中表示:
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. 您必须分两步构建通用
IEnumerable
类型。 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>>>());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.