title: MVC, EF - DataContext singleton instance Per-Web-Request in Unity
body: <p>I have a MVC 3 web application, where I am using the Entity Framework for the data access. Furthermore, I have made a simple use of the repository pattern, where e.g. all Product related stuff is handled in the &quot;ProductRepository&quot; and all User related stuff is handled in the &quot;UserRepository&quot;.</p>
  <p>Thus, I am using the UNITY container, to make a singleton instance of the DataContext, which I inject into each of the repositories. A quick search on Google, and everyone recommends you to NOT use a singleton instance of the DataContext, as it might give you some memory leaks in the future.</p>
  <p>So, inspired by this post, making a singleton instance of the DataContext for each web request is the answer (please correct me if I am wrong!)</p>
  <p><a href="http://blogs.microsoft.co.il/blogs/gilf/archive/2010/05/18/how-to-manage-objectcontext-per-request-in-asp-net.aspx" rel="nofollow noreferrer">http://blogs.microsoft.co.il/blogs/gilf/archive/2010/05/18/how-to-manage-objectcontext-per-request-in-asp-net.aspx</a></p>
  <p>However, UNITY does not support the &quot;Per-web-request&quot; lifetime manager. But, it is possible to implement your own custom lifetime manager, which handles this for you. Actually, this is discussed in this post :</p>
  <p><a href="https://stackoverflow.com/questions/1151201/singleton-per-call-context-web-request-in-unity">Singleton Per Call Context (Web Request) in Unity</a></p>
  <p>The question is, I have now implemented the custom lifetime manager as described in the above post, but I am unsure if this is the way to do it. I am also wondering about where the datacontext instance is disposed in the provided solution? Am I missing out something?</p>
  <p>Is there actually a better way of solving my &quot;issue&quot;?</p>
  <p>Thanks!</p>
  <h2>** Added information about my implementation **</h2>
  <p>The following is snippets from my Global.asax, Controller and Repository. This gives a clear picture of my implementation.</p>
  <p><strong>Global.asax</strong></p>
  <pre><code>  var container = new UnityContainer();
              container
                  .RegisterType&lt;ProductsRepository&gt;(new ContainerControlledLifetimeManager())
                  .RegisterType&lt;CategoryRepository&gt;(new ContainerControlledLifetimeManager())
                  .RegisterType&lt;MyEntities&gt;(new PerResolveLifetimeManager(), dbConnectionString)
  </code></pre>
  <p><strong>Controller</strong></p>
  <pre><code>private ProductsRepository _productsRepository;
  private CategoryRepository _categoryRepository;
  
  public ProductsController(ProductsRepository productsRepository, CategoryRepository categoryRepository)
  {
     _productsRepository = productsRepository;
     _categoryRepository = categoryRepository;
  }
  
  public ActionResult Index()
  {
     ProductCategory category = _categoryRepository.GetProductCategory(categoryId);
     . 
     . 
     . 
  }
  
  protected override void Dispose(bool disposing)
  {
      base.Dispose(disposing);
      _productsRepository.Dispose();
      _categoryRepository.Dispose();
  }
  </code></pre>
  <p><strong>Product Repository</strong></p>
  <pre><code>public class ProductsRepository : IDisposable
  {
  
  private MyEntities _db;
  
  public ProductsRepository(MyEntities db)
  {
      _db = db;
  }
  
  public Product GetProduct(Guid productId)
  {
      return _db.Product.Where(x =&gt; x.ID == productId).FirstOrDefault();
  }
  
  public void Dispose()
  {
      this._db.Dispose();
  }
  </code></pre>
  <p><strong>Controller Factory</strong></p>
  <pre><code>public class UnityControllerFactory : DefaultControllerFactory
  {
      IUnityContainer _container;
  
      public UnityControllerFactory(IUnityContainer container)
      {
          _container = container;
      }
  
      protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
      {
          if (controllerType == null)
          {
              throw new HttpException(404, String.Format(&quot;The controller for path '{0}' could not be found&quot; +
                  &quot;or it does not implement IController.&quot;,
                   requestContext.HttpContext.Request.Path));
          }
  
          return _container.Resolve(controllerType) as IController;
      }
  
  }
  </code></pre>
  <p><strong>Addition information</strong>
  Hi, I will post additional links that I come across, concerning the related issue and solution suggestions:</p>
  <ol>
  <li><a href="https://github.com/geersch/EntityFrameworkObjectContext" rel="nofollow noreferrer">https://github.com/geersch/EntityFrameworkObjectContext</a></li>
  <li><a href="http://dotnetslackers.com/articles/ado_net/Managing-Entity-Framework-ObjectContext-lifespan-and-scope-in-n-layered-ASP-NET-applications.aspx" rel="nofollow noreferrer">http://dotnetslackers.com/articles/ado_net/Managing-Entity-Framework-ObjectContext-lifespan-and-scope-in-n-layered-ASP-NET-applications.aspx</a></li>
  <li><a href="https://stackoverflow.com/questions/2482220/attaching-linq-to-sql-datacontext-to-httpcontext-in-business-layer">attaching linq to sql datacontext to httpcontext in business layer</a></li>
  <li><a href="http://weblogs.asp.net/shijuvarghese/archive/2008/10/24/asp-net-mvc-tip-dependency-injection-with-unity-application-block.aspx" rel="nofollow noreferrer">http://weblogs.asp.net/shijuvarghese/archive/2008/10/24/asp-net-mvc-tip-dependency-injection-with-unity-application-block.aspx</a></li>
  <li><a href="http://msdn.microsoft.com/en-us/library/bb738470.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/bb738470.aspx</a></li>
  </ol>