caSTLe-windsor - Circular 'interfaces' 依赖项和 CaSTLe-Windsor

标签 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 为空。
如何配置 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 进行此类配置?

最佳答案

通常,像这样的循环引用是一个坏主意™,而 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 - Circular 'interfaces' 依赖项和 CaSTLe-Windsor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2463895/

相关文章:

asp.net-web-api - 使用 Windsor CasSTLe 拦截 webpi2 调用

dependency-injection - 温莎城堡 : OnCreate for BaseOnDescriptor

caSTLe-windsor - 温莎的通用类型工厂

asp.net - CaSTLe Windsor Controller 工厂和存储库未解析

asp.net-mvc - 使用 CaSTLe Windsor 在 ASP.NET MVC 中实现 Multi-Tenancy 的最佳实践是什么?

c# - 如何获取 IWindsorContainer 中已注册程序集的列表 (C#)

c# - Moq 单元测试 Moq.Proxy.CaSTLeProxyFactory 上的 : System. TypeInitializationException

c#-4.0 - CaSTLe Windsor 3.0、服务和多重实现

caSTLe-windsor - 温莎安装程序配置

c# - 使用 CaSTLe 注入(inject)具有非通用实现的开放通用接口(interface)