循环’接口’依赖和Castle-Windsor

我有组件:

public interface IFoo
{ }

public interface IBar
{ }

public class Foo : IFoo
{
    public IBar Bar { get; set; }
}

public class Bar : IBar
{
    public IFoo Foo { get; set; }
}

我有Castle-Windsor配置:

Container.AddComponent("IFoo", typeof (IFoo), typeof (Foo));
Container.AddComponent("IBar", typeof (IBar), typeof (Bar));

和单元测试失败:

[Test]
public void FooBarTest()
{
    var container = ObjFactory.Container;

    var foo = container.Resolve<IFoo>();
    var bar = container.Resolve<IBar>();

    Assert.IsNotNull(((Foo) foo).Bar);
    Assert.IsNotNull(((Bar) bar).Foo);
}

它失败了,因为循环依赖,“foo”.Bar或“bar”.Foo为null.
如何配置Castle以正确初始化两个组件?

我可以手动正确初始化两个组件:

[Test]
public void FooBarTManualest()
{
    var fooObj = new Foo();
    var barObj = new Bar();

    fooObj.Bar = barObj;
    barObj.Foo = fooObj;

    var foo = (IFoo) fooObj;
    var bar = (IBar) barObj;

    Assert.IsNotNull(((Foo)foo).Bar);
    Assert.IsNotNull(((Bar)bar).Foo);
}

..它有效,通过.
如何使用Castle Windsor进行此类配置?

最佳答案
通常像这样的循环引用是Bad Idea™,而Windsor不解决它们,所以这部分你必须手动完成:

        var container = new WindsorContainer();
        container.Register(Component.For<IFoo>().ImplementedBy<Foo>()
                            .OnCreate((k, f) =>
                                        {
                                            var other = k.Resolve<IBar>() as Bar;
                                            ((Foo)f).Bar = other;
                                            other.Foo = f;
                                        }),
                           Component.For<IBar>().ImplementedBy<Bar>());
        var foo = container.Resolve<IFoo>() as Foo;
        var bar = container.Resolve<IBar>() as Bar;

        Debug.Assert(bar.Foo != null);
        Debug.Assert(foo.Bar != null);
        Debug.Assert((foo.Bar as Bar).Foo == foo);
        Debug.Assert((bar.Foo as Foo).Bar == bar);

然而,真正需要这种循环是非常罕见的.您可能想要修改您的设计.

转载注明原文:循环’接口’依赖和Castle-Windsor - 代码日志