C# 如何在AutoFac中注册具有接口类型的通用接口?

C# 如何在AutoFac中注册具有接口类型的通用接口?,c#,.net,generics,interface,autofac,C#,.net,Generics,Interface,Autofac,我正在尝试使用Autofac注册具有多种类型的通用接口,我想调用: container.Resolve<Enumerable<IGenericInterface<IInterface>>>(); container.Resolve(); 使用I接口类型解析IGenericInterface的所有实现 我已经尝试将具有泛型接口的具体类注册为具有接口的泛型接口: builder.Register(r => new TalkToMeLoud())

我正在尝试使用Autofac注册具有多种类型的通用接口,我想调用:

container.Resolve<Enumerable<IGenericInterface<IInterface>>>(); 
container.Resolve();
使用I接口类型解析IGenericInterface的所有实现

我已经尝试将具有泛型接口的具体类注册为具有接口的泛型接口:

builder.Register(r => new TalkToMeLoud())
    .As<IGenericInterface<Hello>>()
    .As<IGenericInterface<Bye>>()
    .As<IGenericInterface<IInterface>>()
    .InstancePerDependency();
builder.Register(r=>new TalkToMeLoud())
.As()
.As()
.As()
.InstancePerDependence();
但这将抛出一个错误:

Autofac.dll中发生“System.ArgumentException”类型的未处理异常

其他信息:“TestConsoleEapp.TalkToCloud”类型不能分配给服务“TestConsoleEapp.IGenericInterface`1[[TestConsoleEapp.IInterface,TestConsoleEapp,Version=1.0.0.0,Culture=neutral,PublicKeyToken=null]]”

因为这是从Unity到Autofac迁移的一部分,我知道Unity可以这样做:

Container.ResolveAll(typeof(IGenericInterface<IInterface>))
Container.ResolveAll(typeof(IGenericInterface))
有人知道如何解决这个问题吗


注:这是我的

信息非常清楚:

“TalkToCloud”类型不能分配给服务“IGenericInterface”

换句话说,您必须:

  • TalkToCloud
    上执行
    IGenericInterface
    ,或
  • 通过将
    T
    设置为
    out
    参数,使
    IGenericInterface
    协变。i、 e.
    IGenericInterface
CLR将无法将
TalkToCloud
转换为
IGenericInterface
,即使它可能实现
IGenericInterface
,其中
Hello
实现
IInterface
。如果你不熟悉方差的概念,你可能会想在谷歌上搜索一下,然后像这样阅读答案


因此,在您的情况下,您可能需要使您的接口协调;这允许您从
IGenericInterface
转换到
IGenericInterface
。但是,只有当
T
仅用作接口中的输出参数时,这才有效。

感谢您提供的信息,这对我很有帮助,但是您知道为什么Unity可以用IEnumerable解决所有实现,而autofac不能解决所有实现吗?@donlobbo:如果
IGenericInterface
不是变体,Unity返回的列表应为空。如果没有,请更新您的问题以显示:1。你的接口定义,2。你的统一配置3。解析该可枚举项时解析哪些实现,以及4这些实现的定义。