当 ninject 内的弱引用集合中没有对象被处理时内存泄漏,我做错了什么或者 ninject 中是否存在巨大错误?
当内核被释放时,所有引用都被释放,来自弱引用集合,但是在这个循环中,即使没有来自代码的引用 - 内存也会爆炸。
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();
}
}