title: What is best practice for using Unity with Entity Framework in a MVC 4 application
body: <p>I'm struggling with Entityframework in a MVC 4 app, making use of Unity for Dependency injection and Automapper for automapping object to DTO. I run from one issue to the other, EF is sometimes returning old data, so I think my design is not good enough.</p>
  
  <p>What do I have:</p>
  
  <p>To configure Unity I have in my Application_Start:</p>
  
  <pre><code>var UnityContainer = UnityConfig.GetConfiguredContainer();
  Mapper.Initialize(cfg =&gt; cfg.ConstructServicesUsing(type =&gt; UnityContainer.Resolve(type)));
  UnityContainer.Resolve&lt;AutoMapperConfig&gt;().MapAutoMapper();
  ...
  </code></pre>
  
  <p>In UnityConfig.RegisterTypes:</p>
  
  <pre><code>container.RegisterType&lt;IMyContext, MyContext&gt;(new ContainerControlledLifetimeManager())
  ...
  </code></pre>
  
  <p>My respositories use constructor depencency injection:</p>
  
  <pre><code>public class MSSQLTenantRepository : IDalTenantRepository
  {
     private readonly IMyContext _Db;
     public MSSQLTenantRepository(IMyContext db)
     {
        Db = db;
     }
  ...
  </code></pre>
  
  <p>And my controller use constructor dependency injection too:</p>
  
  <pre><code>public class TenantController : Controller
  {
     private readonly ITenantRepository _TenantRepository;
     public TenantController(ITenantRepository tenantRepository,
     {
        _TenantRepository = tenantRepository;
     }
  ...
  </code></pre>
  
  <p>Automapper config:</p>
  
  <pre><code>public class AutoMapperConfig
  {
      private readonly ITenantRepository _TenantRepository;
      public AutoMapperConfig(ITenantRepository tenantRepository)
      {
          _TenantRepository = tenantRepository;
      }
  ...
  </code></pre>
  
  <p>Issues:
  I sometimes get old data, from the first request.</p>
  
  <p>When I manually update the data in de SQL server, EF's returning object don't reflect the changes</p>
  
  <p>When I tried different options I also got error about multiple context (due to Automapper)</p>
  
  <p>My questions:</p>
  
  <ul>
  <li>What is best practice using Unity, MVC4, EF 6, repositories and Automapper?</li>
  <li>Where to put the code (e.g. in global.asax.c or in UnitiConfig.cs of UnityWebApiActivator?</li>
  <li>Do I need to explicit dispose the dbcontext, and if so: Where to do this?</li>
  </ul>
  
  <p>There is a lot said about this subject, but nothing covers all.</p>