使用LifestyleTransient时,Windsor工厂不会创建新对象

时间:2016-02-26 13:28:02

标签: c# castle-windsor

我有一种情况,我将制作对象,但我需要使用Windsor来获取对其他对象的引用。我没有太多的经验,这篇文章的标题可能会误导......所以我环顾网络,发现这个Why would you use Windsor AsFactory?并决定先尝试使用这个例子。所以我创造了这个:

public interface INumberWriterFactory
{
    INumberWriter Create(int number);
    INumberWriter Create(int number, IDependencyThatIWillNeed dependency);

}

public interface INumberWriter
{
    void Write();
}

public class NumberWriter : INumberWriter
{
    private int _number;
    private IDependencyThatIWillNeed _dependency;

    public NumberWriter(int number, IDependencyThatIWillNeed dependency)
    {
        _number = number;
        _dependency = dependency;
    }

    public void Write()
    {
        System.Diagnostics.Debug.WriteLine("Inside: " + _number);
    }
}

我注册了这些(AddFacility<TypedFactoryFacility>()之前在某处注册过):

container.Register(
    Component.For<INumberWriterFactory>().AsFactory().IsDefault(),
    Component.For<INumberWriter>().ImplementedBy<NumberWriter>().LifestyleTransient().IsDefault());

执行如下代码:

var _numberWriterFactory = _container.Resolve<INumberWriterFactory>();

var list = new List<int> { 105042, 162306, 29443 };
foreach (var i in list)
{
    System.Diagnostics.Debug.WriteLine("Outside: " + i);
    var numberWriter = _numberWriterFactory.Create(i);
    numberWriter.Write();
}

但输出如下:

Outside: 105042
Inside: 105042
Outside: 162306
Inside: 105042
Outside: 29443
Inside: 105042

我无法理解 - 它为什么不起作用? INumberWriter已注册为LifestyleTransient,因此每次都应创建新实例,对吧?嗯,事实并非如此。 NumberWriter的构造函数只到达一次。

基本上 - 如何创建具有依赖关系的新对象?

0 个答案:

没有答案