title: Entity Framework Object Context in ASP.NET Session object?
body: <p>We have a multi-layered Asp.NET Web Forms application. The data layer has a class called <code>DataAccess</code> which impements <code>IDisposable</code> and has an instance of our Entity Framework Object Context as a private field. The class has a number of public methods returning various collections of Entities and will dispose its Object Context when it is disposed. </p>
  
  <p>Due to a number of problems we've been facing, we decided it would be a big plus to keep the Object Context (or an instance of <code>DataAccess</code>) in scope for longer on the server. A suggestion was made to keep an instance in the <code>HttpContext.Current.Items</code> collection from <a href="http://dotnetslackers.com/articles/ado_net/managing-entity-framework-objectcontext-lifespan-and-scope-in-n-layered-asp-net-applications.aspx" rel="noreferrer">this post</a> in order to have one instance per Http request.</p>
  
  <p>What I'm wondering is: What issues / concerns / problems would arise from storing an instance of our Object Context in the <code>HttpContext.Current.Session</code> object????</p>
  
  <ul>
  <li>I'm assuming that the Session object is finalised and set for garbage collection when a user's session expires, so the instance will be disposed properly.</li>
  <li>I'm assuming most default browser settings will let our app place its SessionId cookie without qualms.</li>
  <li>The amount of data the Object Context will be dealing with is not enormous and will not pose a problem for our decent server hardware, with regards to caching over time and relatively few concurrent users.</li>
  </ul>
  
  <p>This will be relatively quick to implement and will not affect our many existing unit tests. </p>
  
  <p>We'll be using AutoFac and a ServiceProvider class to supply instances. When an instance of the ObjectContext is required it will be returned by code similar to this:</p>
  
  <pre><code>private static Entities GetEntities(IContext context)
  {
      if (HttpContext.Current == null)
      {
          return new Entities();
      }
  
      if (HttpContext.Current.Session[entitiesKeyString] == null)
      {
          HttpContext.Current.Session[entitiesKeyString] = new Entities();
      }
  
      return (Entities)HttpContext.Current.Session[entitiesKeyString];
  }
  </code></pre>
  
  <p>Cheers.</p>