title: One object per HttpContext instance
body: <p>I'm currently writing a project in ASP.NET MVC. I have a web project and DB project which solely works with DB. The layers look like this and they interoperate only with sibling layers.</p>
  
  <p><b>DB project (EF CF) </b> - makes db requests</p>
  
  <p><b>Repository</b> - abstracting the underlying db model</p>
  
  <p><b>Service</b> - All business logic happenes here.</p>
  
  <p><b>ASP.NET MVC Web application</b> - Front end presentation</p>
  
  <p>They must be loosely coupled so I'm using Unity DI/IoC framework</p>
  
  <p>What I want to achieve is to create one instance of <code>DbContext</code> per http request. The following is the logic I implemented so far.</p>
  
  <pre><code>public class MyAppBaseController : Controller {
      protected override void OnActionExecuting(ActionExecutingContext filterContext) {
          if (HttpContext.Items["DbModel"] == null) {
              HttpContext.Items["DbModel"] = MySingleton.Container.Resolve&lt;DbContext&gt;();
          }
          base.OnActionExecuting(filterContext);
      }
  }
  </code></pre>
  
  <p>What is does is that in request pipeline if the <code>Items</code> dictionary of the current <code>HttpContext</code> doesn't have <code>DbContext</code>, it adds one. All controllers inherit from it. The reason why I'm doing so is that all repositories that will be called during execution should use exactly the same <code>DbContext</code> object for all sequential db calls.</p>
  
  <ol>
  <li>Is there a better way to couple the lifetime of the object with the <code>HttpContext</code>?</li>
  <li>Is it possible to do it using Unity (DI/IoC framework)?</li>
  </ol>