[英]Registercollection open generic type
Simple Injector 4可以进行以下操作吗?
var types = container.GetTypesToRegister(typeof(IFoo<>), assemblies);
container.RegisterCollection(typeof(IFoo<>), types);
与
public interface IFoo<T> where T : IBar { ... }
和
public interface IBar { ... }
在装配中,类似的类型如下所示:
public class Foo : IFoo<FooBar> { ... }
哪里
public class FooBar : IBar { ... }
容器验证此注册。 但是当我这样做
container.GetAllInstances<IFoo<IBar>>();
然后结果为空。 我的意图是注入以下内容:
IEnumerable<IFoo<IBar>> foos
我希望它返回IFoo<>
所有封闭类型实现,其中封闭的通用参数是IBar
的实现。
还有一点是,每当我想为使用IEnumerable<IFoo<IBar>>
的服务编写单元测试时,我都会尝试使用以下方法对此进行模拟:
IEnumerable<IFoo<IBar>> collection = new[] { new Foo() };
new ConsumerService(collection);
在这里,编译器很难将类型Foo
转换为IFoo<IBar>
,我想我理解(不确定。)。 但是我不明白的是,简单注入器将如何实例化集合中的类型?
为了实现您想要的功能,您将必须创建IFoo<T>
接口变体。
你会得到一个空列表的原因是因为IFoo<IBar>
是不是从分配IFoo<FooBar>
。 自己尝试:C#编译器不允许您将Foo
IFoo<IBar>
为IFoo<IBar>
。
为此,您必须使IFoo<T>
协变量。 换句话说,您需要如下定义接口:
public interface IFoo<out T> { }
完成此操作后,您将看到Simple Injector会自动为您解析所有实例。
但是,使用out
类型参数是否对您有用吗是另一个问题。 鉴于您给出的抽象描述,我无法回答。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.