Autofac - 在运行时解析IEnumerable通用接口

Mic*_*aly 3 c# autofac

我发现如何使用下面的代码在运行时解析通用接口.如何IGenericInterface<>在运行时解析所有返回集合的实例.我知道在autofac我们应该使用IEnumerable<T>但我不知道如何在下面的例子中表示:

 var typeInRuntime = typeof (SubClass1);
 var instance1 = container.Resolve(typeof(IGenericInterface<>)
                          .MakeGenericType(typeInRuntime));
Run Code Online (Sandbox Code Playgroud)

这显然不起作用

 var typeInRuntime = typeof (SubClass1);
 var collection = container
                .Resolve(IEnumerable<typeof(IGenericInterface<>)
                .MakeGenericType(typeInRuntime)>);
Run Code Online (Sandbox Code Playgroud)

Pet*_*old 5

您必须IEnumerable分两步构建泛型类型.以下代码适用于我的机器;)

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>>>());
Run Code Online (Sandbox Code Playgroud)