我正在尝试使用Autofac注册多个类型的通用接口,我想调用:
container.Resolve<Enumerable<IGenericInterface<IInterface>>>();
使用一种IInterface来解决所有IGenericInterface的实现。
我已经尝试将具有通用接口和具体类的具体类注册为接口的通用接口:
builder.Register(r => new TalkToMeLoud())
.As<IGenericInterface<Hello>>()
.As<IGenericInterface<Bye>>()
.As<IGenericInterface<IInterface>>()
.InstancePerDependency();
但这会引发错误:
Autofac.dll中出现未处理的“System.ArgumentException”类型异常
其他信息:“TestConsoleApp.TalkToMeLoud”类型不能分配给服务'TestConsoleApp.IGenericInterface`1 [[TestConsoleApp.IInterface,TestConsoleApp,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null]]'。< / p>
因为这是从Unity迁移到Autofac的一部分,我知道Unity可以这样做:
Container.ResolveAll(typeof(IGenericInterface<IInterface>))
有谁知道如何解决这个问题?
PS:这是我的testproject
答案 0 :(得分:0)
信息很清楚:
“TalkToMeLoud”类型不能分配给服务“IGenericInterface”。
换句话说,你要么:
IGenericInterface<IInterface>
或TalkToMeLoud
IGenericInterface<T>
设置为T
参数,使out
协变。即IGenericInterface<out T>
。 CLR将无法将TalkToMeLoud
投射到IGenericInterface<IInterface>
,即使它可能会IGenericInterface<Hello>
实施Hello
IInterface
。如果您不熟悉方差概念,您可能需要进行一些谷歌搜索并阅读this one等答案。
因此,在您的情况下,您可能需要使您的界面保持稳定;这允许您从IGenericInterface<Hello>
投射到IGenericInterface<IInterface>
。这仅在T
仅用作接口中的输出参数时才有效。