用Unity填充集合的方法
我有两个示例类
class ClassToResolve
{
private List<CollectionItem> _coll;
public ClassToResolve(List<CollectionItem> coll)
{
_coll = coll;
}
}
class CollectionItem
{
//...
}
,我需要解析 ClassToResolve
var classToResolve = new ClassToResolve(
new List<CollectionItem>()
{
new CollectionItem(),
new CollectionItem(),
new CollectionItem()
}
);
现在我以某种方式解析
var classToResolve = new ClassToResolve(
new List<CollectionItem>()
{
unity.Resolve<CollectionItem>(),
unity.Resolve<CollectionItem>(),
unity.Resolve<CollectionItem>()
}
);
它 有没有办法使用动态注册通过 Unity 解析 ClassToResolve?
I have two example classes
class ClassToResolve
{
private List<CollectionItem> _coll;
public ClassToResolve(List<CollectionItem> coll)
{
_coll = coll;
}
}
class CollectionItem
{
//...
}
and I need to resolve ClassToResolve
var classToResolve = new ClassToResolve(
new List<CollectionItem>()
{
new CollectionItem(),
new CollectionItem(),
new CollectionItem()
}
);
Now I resolve it in a way
var classToResolve = new ClassToResolve(
new List<CollectionItem>()
{
unity.Resolve<CollectionItem>(),
unity.Resolve<CollectionItem>(),
unity.Resolve<CollectionItem>()
}
);
Is there a way to resolve ClassToResolve with Unity using dynamic registration?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Unity 将理解
T[]
(数组)依赖项是一个事物列表(但不是IEnumerable
,也不是List
)。当您更改ClassToResolve
的构造函数以采用CollectionItem[]
而不是List
时,您可以配置您的CollectionItem< /code> 类型如下:
这里的技巧是为所有注册命名。默认(无名)注册永远不会成为 Unity 中序列依赖关系的一部分。
现在您可以解析
ClassToResolve
而无需注册它:如果您更愿意注入
List
,您可以添加以下注册:对于
IEnumerable
您可以添加以下行:Unity will understand that
T[]
(array) dependencies are a list of things (but notIEnumerable<T>
, norList<T>
). When you change the constructor ofClassToResolve
to take anCollectionItem[]
instead of aList<CollectionItem>
you can configure yourCollectionItem
types as follows:The trick here is to name all the registrations. A default (nameless) registration will never be part of a sequence dependency in Unity.
Now you can resolve
ClassToResolve
without the need to register it:If you rather inject
List<CollectionItem>
you can add the following registration:And for
IEnumerable<CollectionItem>
you can add the following line:@Steven 的答案完全正确,我只是想建议另一种方法来解决这个问题。
为了获得更好、更简洁的代码,为所有集合项定义一个接口是值得的。
现在 Unity 容器的注册代码会更容易:
并且解析代码是相同的:
我希望 Microsoft 在下一版本的 Unity 中添加
IEnumerable
支持,这样我们就不需要注册IEnumerable
。@Steven's answer is perfectly correct, I just want to suggest another way to tackle the issue.
For the sake of a better and cleaner code, it is worth it to define an interface for all the collection items.
Now the registration code for Unity container would be much more easier:
and the resolve code is the same:
I hope Microsoft add
IEnumerable<>
support to the next version of Unity so we won't need to registerIEnumerable<IMyClass>
.你应该在统一中注册你的类
最好使用接口
You should register you class in unity
It's better to use interface
用这个
Use this