Windsor TypedFactoryInterceptor内存泄漏

时间:2011-07-22 02:02:35

标签: .net memory-leaks castle-windsor

我认为TypedFactoryInterceptor存在内存泄漏。

请考虑以下情况:

[Factory]
public interface IMyFactory 
{
     MySingleton GetInstance();
}

[Singleton]
public class MySingleton
{
}

[Singleton]
public class MyController
{
    public MyController(IMyFactory factory)
    {
        // using a for loop to simulate repeated calls to the factory instance over
        // a long time
        for(int i = 0; i < 100000; i++)
        {
            var instance = factory.GetInstance();
        }
    }
}

在上面的例子中,TypedFactoryInterceptor将包含一个100000 WeakReferences的列表,所有这些WeakReferences都指向同一个Target实例(MySingleton)。因此,在一个单例依赖于工厂来创建另一个单例的实例的情况下,最终可能会有数十万个WeakReferences,从而导致内存泄漏。

在查看源代码时,看起来问题就在这里(在TypedFactoryInterceptor.Resolve中):

// this is called on every Resolve call to the TypedFactory (IMyFactory.GetInstance)
if (this.kernel.ReleasePolicy.HasTrack(instance))
{
    // there will not be any dead references because MySingleton is a Singleton
    this.CollectDeadReferences();
    // adds another WeakReference to the same Singleton instance
    this.resolvedTrackedComponents.Add(new WeakReference(instance));
}

有什么想法吗?

感谢。

1 个答案:

答案 0 :(得分:1)

这是因为WeakReference是Windsor 2.5中架构限制的一种解决方法,而不是一个完整的解决方案。

这已在(即将推出的)Windsor 3中修复,其中不涉及WeakReference

作为一种临时解决方法,我猜你最好的选择是不要为那个单身人士使用工厂(或升级到Windsor 3)。

相关问题