我有两个示例类

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?

最佳答案

Unity将理解T[](数组)依赖项是事物的列表(但不是IEnumerable<T>,也不是List<T>)。当您将ClassToResolve的构造函数更改为采用CollectionItem[]而不是List<CollectionItem>时,可以按以下方式配置CollectionItem类型:

container.RegisterType<CollectionItem, CollectionItemA>("a");
container.RegisterType<CollectionItem, CollectionItemB>("b");
container.RegisterType<CollectionItem, CollectionItemC>("c");
container.RegisterType<CollectionItem, CollectionItemD>("d");

这里的窍门是命名所有注册。默认(无名)注册永远不会成为Unity中序列依赖项的一部分。

现在,您无需注册即可解析ClassToResolve:
container.Resolve<ClassToResolve>();

如果您想注入(inject)List<CollectionItem>,则可以添加以下注册:
container.RegisterType<IList<CollectionItem>, CollectionItem[]>();

对于IEnumerable<CollectionItem>,您可以添加以下行:
container
  .RegisterType<IEnumerable<CollectionItem>, CollectionItem[]>();

10-06 13:26