title: Entity Framework, DBContext and using() + async?
body: <p>There is a thing that's been bugging me for a long time about Entity Framework.</p>
  
  <p>Last year I wrote a big application for a client using EF. And during the development everything worked great.</p>
  
  <p>We shipped the system in august. But after some weeks I started to see weird memory leaks on the production-server. My ASP.NET MVC 4 process was taking up all the resources of the machine after a couple of days running (8 GB). This was not good. I search around on the net and saw that you should surround all your EF queries and operations in a <code>using()</code> block so that the context can be disposed.</p>
  
  <p>In a day I refactored all my code to use <code>using()</code> and this solved my problems, since then the process sits on a steady memory usage.</p>
  
  <p>The reason I didn't surround my queries in the first place however is that I started my first controllers and repositories from Microsofts own scaffolds included in Visual Studio, these did not surround it's queries with using, instead it had the <code>DbContext</code> as an instance variable of the controller itself. </p>
  
  <p><strong>First of all</strong>: if it's really important to dispose of the context (something that wouldn't be weird, the <code>dbconnection</code> needs to be closed and so on), Microsoft maybe should have this in all their examples!</p>
  
  <p>Now, I have started working on a new big project with all my learnings in the back of my head and I've been trying out the new features of .NET 4.5 and EF 6 <code>async</code> and <code>await</code>. EF 6.0 has all these async methods (e.g <code>SaveChangesAsync</code>, <code>ToListAsync</code>, and so on).</p>
  
  <pre><code>public Task&lt;tblLanguage&gt; Post(tblLanguage language)
  {
      using (var langRepo = new TblLanguageRepository(new Entities()))
      {
          return langRepo.Add(RequestOrganizationTypeEnum, language);
      }
  }
  </code></pre>
  
  <p>In class <code>TblLanguageRepo</code>:</p>
  
  <pre><code>public async Task&lt;tblLanguage&gt; Add(OrganizationTypeEnum requestOrganizationTypeEnum, tblLanguage language)
  {
      ...
      await Context.SaveChangesAsync();
      return langaugeDb;
  }
  </code></pre>
  
  <p>However, when I now surround my statements in a <code>using()</code> block I get the exception, <code>DbContext was disposed</code>, before the query has been able to return. This is expected behaviour. The query runs async and the <code>using</code> block is finished ahead of the query. But how should I dispose of my context in a proper way while using the async and await functions of ef 6??</p>
  
  <p>Please point me in the right direction.</p>
  
  <p>Is <code>using()</code> needed in EF 6? Why do Microsoft's own examples never feature that? How do you use async features and dispose of your context properly?</p>