为什么Windsor的Typed Factory会传递给它第一次收到的构造函数参数?

时间:2012-08-09 13:39:23

标签: .net dependency-injection castle-windsor

以下测试在上一次Assert()失败并显示以下消息:   预计:“arg2”   但是:“arg1”

"arg1"第一次通过时,类型工厂会记住这一点,并忽略第二次调用中的"arg2"。为什么呢?

public class E
{
    public string Arg { get; set; }

    public E(string arg)
    {
        Arg = arg;
    }
}

public interface IEFactory
{
    E Create(string arg);
}

[Test]
public void TypedFactoryWorksAsExpected()
{
    var windsor = new WindsorContainer();
    windsor.Kernel.AddFacility<TypedFactoryFacility>();
    windsor.Register(
        Component.For<E>(), 
        Component.For<IEFactory>().AsFactory());

    var factory = windsor.Resolve<IEFactory>();
    var e1 = factory.Create("arg1");
    var e2 = factory.Create("arg2");

    Assert.AreEqual("arg1", e1.Arg);

    // This line fails with  message: 
    // 'Expected: "arg2" But was: "arg1".'
    Assert.AreEqual("arg2", e2.Arg);
}

1 个答案:

答案 0 :(得分:1)

对于windsor组件,默认情况下是单例。您的E是单身人士,因为您没有指定任何其他内容。第二个调用不会忽略该参数,但重用前一个实例,因为它是一个单例。

您必须定义E是瞬态的:

windsor.Register(Component.For<E>().LifeStyle.Transient);