加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 04:48:18 所属栏目:百科 来源:网络整理
导读:我有组件: 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),
我有组件:

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读