C# 如何在AutoFac中注册具有接口类型的通用接口?
我正在尝试使用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())
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
协变。i、 e.IGenericInterface
IGenericInterface
TalkToCloud
转换为IGenericInterface
,即使它可能实现IGenericInterface
,其中Hello
实现IInterface
。如果你不熟悉方差的概念,你可能会想在谷歌上搜索一下,然后像这样阅读答案
因此,在您的情况下,您可能需要使您的接口协调;这允许您从
IGenericInterface
转换到IGenericInterface
。但是,只有当T
仅用作接口中的输出参数时,这才有效。感谢您提供的信息,这对我很有帮助,但是您知道为什么Unity可以用IEnumerable解决所有实现,而autofac不能解决所有实现吗?@donlobbo:如果IGenericInterface
不是变体,Unity返回的列表应为空。如果没有,请更新您的问题以显示:1。你的接口定义,2。你的统一配置3。解析该可枚举项时解析哪些实现,以及4这些实现的定义。