Memory Leaks when using Entity Framework and Winds

2020-06-23 07:42发布

问题:

I'm having trouble getting the windsor container and entity framework working together and it may be due to a problem I've introduced myself but the net result is that I'm getting a terrible memory leaks caused.

I have my application set up with an EDMX and Repositories and Services and those and the objectcontext are set to perwebrequest in the windsor configuration file I use. However when I look at the memory usage in ANTS memory profiler I see that the object context cache is still being held onto as a reference with the cache despite confirming that Dispose has been called.

And each request more dynamic proxies are getting stuck in memory. If anyone else has managed to get themselves in a pickle like this and can offer me advice to get out of it, it would be greatly appreciated.

回答1:

I've managed to track down and resolve the problem by changing the release settings on the kernal for the windsor container to:

_container.Kernel.ReleasePolicy = new NoTrackingReleasePolicy();

It seems although the windsor container calls the dispose method of perwebrequest components it still hangs on to a reference of them which prevents them being garbage collected.

In this case the object it was holding a reference to was of type ObjectContext. Unfortunately despite disposing of this object the all the dynamic proxies cached in this object still remain effectively meaning that a copy of my database (or at least the parts I was accessing) was being added to memory each request causing it to ramp up.



回答2:

You are probably not disposing objects correctly. Try using "Using" blocks.

Cannot say much more without seeing the code.



回答3:

I had the same problem.

After investigation it seemed that I was missing a call to _container.Release(controller) in my Controller Factory:

    public override void ReleaseController(IController controller)
    {
        _container.Release(controller);

        var disposable = controller as IDisposable;
        if (disposable != null)
        {
            disposable.Dispose();
        }
    }

However, I was also using Windsor 2.1 and adding _container.Release(controller) did not do anything for me.

After updating to v3.1 it seems to work.

Hope this helps.

p.s. ANTS Memory Profiler - lifesaver!