title: Disposing ObjectContext (per-request) after use
body: <p>I am using creating one ObjectContext per-request concept. Technically, I am adding ObjectContext instance to HttpContext.Current.Items. But I do not know how to kill this instance properly. Is it safe to use HttpModule and disposing ObjectContext within? I mean, HttpModule might be called for any kind of request. I do not want to use DI/IoC matters, because the project need to lightweight (no third party libs allowed).</p>
  
  <p>UPDATE: here the simple code:
  Created a per-request ObjectContext (Entities class)</p>
  
  <pre><code>public static class ObjectContextPerRequest
  {
      public const string ObjectKey = "_per_request_context_key";
  
      public static Entities PerRequest
      {
          get
          {
              if (HttpContext.Current.Items[ObjectKey] != null)
              {
                  var eContext = new Entities();
                  HttpContext.Current.Items.Add(ObjectKey, eContext);
  
                  return eContext;
              }
  
              return HttpContext.Current.Items[ObjectKey] as Entities;
          }
      }
  }
  </code></pre>
  
  <p>and a disposer module:</p>
  
  <pre><code>class ObjectContextManagerModule : IHttpModule
  {
      public void Init(HttpApplication context)
      {
          context.EndRequest += (s, e) =&gt; { Dispose(); };
      }
  
      public void Dispose()
      {
          if (HttpContext.Current.Items[ObjectContextPerRequest.ObjectKey] != null)
          {
              var edmx = (ObjectContext)HttpContext.Current.Items[ObjectContextPerRequest.ObjectKey];
              edmx.Dispose();
              edmx = null;
          }
      }
  }
  </code></pre>