类型化工厂设施创建递归嵌套实体

时间:2012-09-24 13:34:05

标签: c# castle-windsor windsor-3.0

当您需要创建一些递归嵌套的东西时,请考虑这种情况,例如:

    public interface IRecurrentTestNodeFactory
    {
        RecurrentTestNode Create(int num);
    }

    public class RecurrentTestNode
    {
        public int Num { get; set; }
        public RecurrentTestNode Child { get; set; }

        public RecurrentTestNode(int num, IRecurrentTestNodeFactory factory)
        {
            Num = num;
            Child = num > 0 ? factory.Create(num - 1) : null;
        }
    }

明显的实施是这样的:

    public class ManualRecurrentTestNodeFactory : IRecurrentTestNodeFactory
    {
        public RecurrentTestNode Create(int num)
        {
            return new RecurrentTestNode(num, this);
        }
    }

    [Test]
    public void ManualRecurrentTest()
    {
        var root = new ManualRecurrentTestNodeFactory().Create(1);
        Assert.NotNull(root);
        Assert.AreEqual(1, root.Num);
        Assert.NotNull(root.Child);
        Assert.AreEqual(0, root.Child.Num);
        Assert.Null(root.Child.Child);
    }

此测试通过。但是如果你试着和温莎的Typed Factory Facility做同样的事情那样:

    [Test]
    public void RecurrentTest()
    {
        var windsor = new WindsorContainer();
        windsor.Kernel.AddFacility<TypedFactoryFacility>();
        windsor.Register(Component.For<IRecurrentTestNodeFactory>().AsFactory());
        windsor.Register(Component.For<RecurrentTestNode>().LifeStyle.Transient);

        var f = windsor.Resolve<IRecurrentTestNodeFactory>();
        var root = f.Create(1);
        Assert.NotNull(root);
        Assert.AreEqual(1, root.Num);
        Assert.NotNull(root.Child);
        Assert.AreEqual(0, root.Child.Num);
        Assert.Null(root.Child.Child);
    }

没有这个例外:

Castle.MicroKernel.ComponentActivator.ComponentActivatorException : ComponentActivator: could not instantiate Tests.RecurrentTestNode
  ----> System.Reflection.TargetInvocationException : Exception has been thrown by the target of an invocation.
  ----> Castle.MicroKernel.CircularDependencyException : Dependency cycle has been detected when trying to resolve component 'Tests.RecurrentTestNode'.
The resolution tree that resulted in the cycle is the following:
Component 'Tests.RecurrentTestNode' resolved as dependency of
    component 'Tests.RecurrentTestNode' which is the root component being resolved.

很明显,为什么这样的代码在服务的情况下可能会失败,但对于工厂而言似乎是不必要的限制。我想留下工厂变体,因为我有一堆容器解析的依赖,而不是普通的int。

1 个答案:

答案 0 :(得分:2)

懒惰地打破循环,而不是在构造函数中。温莎的行为是正确的。