R – Linq to SQL DataContext Windsor IoC memory leak problem

asp.net-mvccastle-windsorinversion-of-controlmemory-leaks

I have an ASP.NET MVC app that creates a Linq2SQL datacontext on a per-web-request basis using Castler Windsor IoC.

For some reason that I do not fully understand, every time a new datacontext is created (on every web request) about 8k of memory is taken up and not released – which inevitably causes an OutOfMemory exception.

If I force garbage collection the memory is released OK.

My datacontext class is very simple:

 public class DataContextAccessor : IDataContextAccessor
 {
    private readonly DataContext dataContext;
    public DataContextAccessor(string connectionString)
    {
        dataContext = new DataContext(connectionString);           
    }
    public DataContext DataContext { get { return dataContext; } }
 }

The Windsor IoC webconfig to instantiate this looks like so:

 <component id="DataContextAccessor"
             service="DomainModel.Repositories.IDataContextAccessor, DomainModel"
             type="DomainModel.Repositories.DataContextAccessor, DomainModel"
             lifestyle="PerWebRequest">       
    <parameters>
      <connectionString>
        ...
      </connectionString>
    </parameters>
  </component>

Does anyone know what the problem is, and how to fix it?

Best Answer

L2S DataContext implements IDisposable. Your interface also has to implement it, and call DataContext.Dispose(), so that Windsor knows that there're resources to be disposed.

By the way beware of Windsor/IDisposable problems: http://www.jeremyskinner.co.uk/2008/05/03/aspnet-mvc-controllers-windsor-and-idisposable/ http://www.nablasoft.com/Alkampfer/?p=105

Related Topic