解析 IEnumerable<T>与团结 [英] Resolving IEnumerable<T> with Unity

查看:28
本文介绍了解析 IEnumerable<T>与团结的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Unity 能否自动解析IEnumerable?

Can Unity automatically resolve IEnumerable<T>?

假设我有一个带有这个构造函数的类:

Let's say I have a class with this constructor:

public CoalescingParserSelector(IEnumerable<IParserBuilder> parserBuilders)

我在容器中配置了单独的 IParserBuilder 实例:

and I configure individual IParserBuilder instances in the container:

container.RegisterType<IParserSelector, CoalescingParserSelector>();
container.RegisterType<IParserBuilder, HelpParserBuilder>();
container.RegisterType<IParserBuilder, SomeOtherParserBuilder>();

我可以在不必实现 IEnumerable 的自定义实现的情况下完成这项工作吗?

can I make this work without having to implement a custom implementation of IEnumerable<IParserBuilder>?

var selector = container.Resolve<IParserSelector>();

到目前为止,我还不能用任何简单的方式表达这一点,但我仍在加强 Unity,所以我可能错过了一些东西.

So far I haven't been able to express this in any simple way, but I'm still ramping up on Unity so I may have missed something.

推荐答案

事实证明,这实际上非常简单:

It turns out that this is actually awfully simple to do:

container.RegisterType<IEnumerable<IParserBuilder>, IParserBuilder[]>();

Unity 本机理解数组,因此我们只需要将可枚举映射到相同类型的数组即可.

Unity natively understands arrays, so we just need to map the enumerable to an array of the same type.

这篇关于解析 IEnumerable&lt;T&gt;与团结的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆