本文介绍了使用Unity填充收集的方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我有两个示例类class ClassToResolve{ private List<CollectionItem> _coll; public ClassToResolve(List<CollectionItem> coll) { _coll = coll; }}class CollectionItem{ //...},我需要解决ClassToResolve and I need to resolve ClassToResolvevar classToResolve = new ClassToResolve( new List<CollectionItem>() { new CollectionItem(), new CollectionItem(), new CollectionItem() } );现在我以某种方式解决了Now I resolve it in a wayvar classToResolve = new ClassToResolve( new List<CollectionItem>() { unity.Resolve<CollectionItem>(), unity.Resolve<CollectionItem>(), unity.Resolve<CollectionItem>() } );有没有办法使用动态注册来解决使用Unity的ClassToResolve? Is there a way to resolve ClassToResolve with Unity using dynamic registration? 推荐答案 Unity将明白 T [] (array)事物列表(但不是 IEnumerable< T> ,而不是列表< T> )。当您将 ClassToResolve 的构造函数更改为采用 CollectionItem [] 而不是列表可以如下配置 CollectionItem 类型:Unity will understand that T[] (array) dependencies are a list of things (but not IEnumerable<T>, nor List<T>). When you change the constructor of ClassToResolve to take an CollectionItem[] instead of a List<CollectionItem> you can configure your CollectionItem types as follows:container.RegisterType<CollectionItem, CollectionItemA>("a");container.RegisterType<CollectionItem, CollectionItemB>("b");container.RegisterType<CollectionItem, CollectionItemC>("c");container.RegisterType<CollectionItem, CollectionItemD>("d");这里的诀窍是命名所有注册。默认(无名)注册将永远不会是Unity中序列依赖关系的一部分。The trick here is to name all the registrations. A default (nameless) registration will never be part of a sequence dependency in Unity.现在您可以解析 ClassToResolve 而不需要注册:Now you can resolve ClassToResolve without the need to register it:container.Resolve<ClassToResolve>();如果你注意列表< CollectionItem> 您可以添加以下注册:If you rather inject List<CollectionItem> you can add the following registration:container.RegisterType<IList<CollectionItem>, CollectionItem[]>();而对于 IEnumerable< CollectionItem> 添加以下行:container .RegisterType<IEnumerable<CollectionItem>, CollectionItem[]>(); 这篇关于使用Unity填充收集的方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 09-25 19:16