简体   繁体   English

使用Unity容器注册递归结构

[英]Registering recursive structure with Unity container

Is it possible to register with the unity container the following recursive structure: 是否可以使用以下递归结构向unity容器注册:

public interface IFoo
{
    IBar[] Bars { get; set; }
}

public interface IBar
{
    IFoo[] Foos { get; set; }
}

Assuming multiple named instances exist for each interface: 假设每个接口都存在多个命名实例:

public class Foo1 : IFoo 
{
    public IBar[] Bars { get; set; }
}

public class Foo2 : IFoo
{
    public IBar[] Bars { get; set; }
}

public class Bar1 : IBar
{
    public IFoo[] Foos { get; set; }
}

public class Bar2 : IBar
{
    public IFoo[] Foos { get; set; }
}

And the registration: 并注册:

var container = new UnityContainer();

container.RegisterType<IFoo, Foo1>("foo1");
container.RegisterType<IFoo, Foo2>("foo2");
container.RegisterType<IBar, Bar1>("bar1");
container.RegisterType<IBar, Bar2>("bar2");

var instanceOfBar = container.Resolve<IBar>("bar1");

How to configure Unity container so that the collection properties are automatically injected? 如何配置Unity容器以便自动注入集合属性?

There is a way to annotate a property to be a dependency. 有一种方法可以将属性注释为依赖项。 But in your case this will not work because of the infiniteness of resolution process. 但在你的情况下,由于解决过程的无限性,这将不起作用。 Simply you will get stackoverflow exception. 简单地说,您将获得stackoverflow异常。 To implement such structures I use lazy pattern so I resolve such collection only if needed: 要实现这样的结构,我使用惰性模式,所以我只在需要时才解决这样的集合:

 Func<IFoo[]> resolver;
 IFoo[] value;
 public IFoo[] Foos { get{
      if(value == null) value = resolver();
         return value;
     } 
 }

to make Func<IFoo[]> resolvable from container add this: 从容器中解析Func<IFoo[]>添加:

 container.RegisterInstance<Func<IFoo[]>>(e => e.Resolve<IFoo[]>());

resolution of array or elements is done out of the box by unity it simply maps to ResolveAll . 数组或元素的分辨率通过统一完成,它只是映射到ResolveAll

Then simply inject Func<IFoo[]> through your constructor. 然后只需通过构造函数注入Func<IFoo[]>

The simple answer to your question is no. 你的问题的简单答案是否定的。 Unity will regard that as a circular reference if, by resolving Foo, you instantiate one or more Bar objects which, in turn, instantiate some Foo objects. 如果通过解析Foo,您将实例化一个或多个Bar对象,然后实例化一些Foo对象,Unity会将其视为循环引用。

Circular references are an issue with Unity: Circular References 循环引用是Unity的一个问题: 循环引用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM