在Ninject中,当WeakReferenceCollection内没有对象被处理时会出现内存泄漏,我错在哪里了?或者是Ninject存在一个巨大的错误吗?
当Kernal被处理掉后,来自WeakReferenceCollection的所有引用都被处理掉,但是当处于此循环中时,即使代码中没有引用,内存也会暴增。
public class Program
{
private StandardKernel kernel;
private static void Main(string[] args)
{
new Program().Run();
}
public void Run()
{
kernel = new StandardKernel(new NinjectSettings() { LoadExtensions = false });
kernel.Bind<Root>().ToSelf();
kernel.Bind<Foo>().ToSelf().InCallScope();
while (true)
{
Process();
Thread.Sleep(500);
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
public void Process()
{
Root root = kernel.Get<Root>();
Root root2 = kernel.Get<Root>();
}
public class Root
{
private Foo _test;
public Root(Foo foofac)
{
Id = Guid.NewGuid();
_test = foofac;
}
protected Guid Id { get; set; }
}
public class Foo
{
}
}
更新
我已经尝试使用命名作用域,甚至像示例中那样使用工厂: http://www.planetgeek.ch/2012/04/23/future-of-activation-blocks/ 但是在内存分析器中,弱引用集合会随着时间的推移而不断增长,这并不好... 我当前的测试代码是:
public class Program
{
private StandardKernel kernel;
private static void Main(string[] args)
{
new Program().Run();
}
public void Run()
{
kernel = new StandardKernel(new NinjectSettings() { LoadExtensions = false });
kernel.Load<FuncModule>();
kernel.Bind<IRootFactory>().ToFactory();
var scopeParameterName = "scopeRoot";
kernel.Bind<Root>().ToSelf().DefinesNamedScope(scopeParameterName);
kernel.Bind<Foo>().ToSelf().InNamedScope(scopeParameterName);
while (true)
{
Process();
GC.Collect();
GC.WaitForPendingFinalizers();
Thread.Sleep(500);
}
}
public void Process()
{
Root root = kernel.Get<IRootFactory>().CreateRoot();
Root root2 = kernel.Get<IRootFactory>().CreateRoot();
}
public class Root
{
private Foo _test;
public Root(Foo foofac)
{
Id = Guid.NewGuid();
_test = foofac;
}
protected Guid Id { get; set; }
}
public class Foo
{
}
public interface IRootFactory
{
Root CreateRoot();
}
}
EndRequest
或我的using( ... CreateNamedScope()
)。在那之前,我依赖于[WCF]InScope(OperationContext.Current)
而没有清理 - 泄漏。 - Ruben Bartelink