title: Singleton Scope for EF's DbContext
body: <p>so I am currently working on an ASP.NET MVC web application that uses Entity Framework, I'm also using Ninject for Dependency Injection.</p>
  
  <p>So basically, at the moment, this is how I register my DbContext and Services with Ninject.</p>
  
  <pre><code>kernel.Bind&lt;DbContext&gt;().To&lt;MyApplicationContext&gt;().InSingletonScope();
  kernel.Bind&lt;IAccountService&gt;().To&lt;AccountService&gt;().InSingletonScope();
  kernel.Bind&lt;IRegionService&gt;().To&lt;RegionService&gt;().InSingletonScope();
  kernel.Bind&lt;IRoleService&gt;().To&lt;RoleService&gt;().InSingletonScope();
  </code></pre>
  
  <p>I register them with <code>InSingletonScope</code>, which means that they will only be created once and used throughout the lifetime of the application (at least how I understand it).</p>
  
  <p>Controllers:</p>
  
  <pre><code>private IAccountService _accountService;
  
  public MemberController(IAccountService accountService)
  {
      _accountService = accountService;
  }
  </code></pre>
  
  <p>However, I have a deep feeling that this singleton scope will cause problem in my web application especially for the Entity Framework's context, due to it being singleton.</p>
  
  <p>I am already facing a minor issue due to this, if I manually update the database using SQL Management Studio, the data in my web application's Entity Framework wouldn't update until I restart the application (seems to be some caching mechanism in EF).</p>
  
  <p>--</p>
  
  <p>However, if I remove the <code>InSingletonScope</code>, I will randomly get errors from EF saying that:</p>
  
  <blockquote>
    <p>An entity object cannot be referenced by multiple instances of IEntityChangeTracker</p>
  </blockquote>
  
  <p>I understand why this happens because the DbContext initialized by <code>AccountService</code> could be different from say, <code>RegionService</code>. But I have no idea how I can resolve this.</p>
  
  <p>My understanding of Dependency Injection is still very limited, so can anybody please advice?</p>
  
  <p>--</p>
  
  <p><strong>EDIT:</strong> I've tried changing to <code>InRequestScope</code> for all the injections, but I'm still getting </p>
  
  <blockquote>
    <p>An entity object cannot be referenced by multiple instances of IEntityChangeTracker</p>
  </blockquote>
  
  <p>When trying to insert a new entity with related object (foreign key) from another service in my application. That means they are still using a different DbContext, what is happening?!</p>
  
  <p><strong>FINAL EDIT:</strong> Ok I've found the problem, it was my caching mechanism that was caching a previous request, causing the relationship issue on all subsequent request.</p>