Circular 'interfaces' dependencies and Castle-Windsor

China☆狼群 提交于 2019-11-30 18:22:01

问题


I've got components:

public interface IFoo
{ }

public interface IBar
{ }

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

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

I've got Castle-Windsor configuration:

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

and failing unit test:

[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);
}

It fails, because of circular dependency, "foo".Bar or "bar".Foo is null. How can I configure Castle to initialize both components properly?

I can initialize properly both components manually:

[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);
}

.. and it works, passes. How to make such configuration using Castle Windsor?


回答1:


Generally circular references like this are a Bad Idea™ and Windsor does not resolve them, so this part you'd have to do manually:

        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);

However it's is quite uncommon to really need this circularity. You may want to revise your design.



来源:https://stackoverflow.com/questions/2463895/circular-interfaces-dependencies-and-castle-windsor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!