title: How should I manage DbContext Lifetime in MVC Core?
body: <p>From the <a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection" rel="noreferrer">Documentation</a></p>
  
  <blockquote>
    <p>Entity Framework contexts <strong>should</strong> be added to the services container
    using the <code>Scoped</code> lifetime. This is taken care of automatically if you
    use the helper methods as shown above. Repositories that will make use
    of Entity Framework should use the same lifetime.</p>
  </blockquote>
  
  <p>I always thought, that I should create a new <code>Context</code> for every single unit of work I have to process. This let me think, if I have a <code>ServiceA</code> and <code>ServiceB</code>, which are applying different actions on the <code>DbContext</code> that they should get a different Instance of <code>DbContext</code>.</p>
  
  <p>The <a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection" rel="noreferrer">documentation</a> reads as following:</p>
  
  <blockquote>
    <ul>
    <li><p><code>Transient</code> objects are always different; a new instance is provided to every controller and every service.</p></li>
    <li><p><code>Scoped</code> objects are the same within a request, but different across different request</p></li>
    </ul>
  </blockquote>
  
  <p>Going back to <code>ServiceA</code> and <code>ServiceB</code>, it sounds to me, <code>Transient</code> is more suitable.</p>
  
  <p>I have researched, that the Context should only saved once per <code>HttpRequest</code>, but I really do not understand how this does work.</p>
  
  <p>Especially if we take a look at one Service:</p>
  
  <pre><code>using (var transaction = dbContext.Database.BeginTransaction())
  {
      //Create some entity
      var someEntity = new SomeEntity();
      dbContext.SomeEntity.Add(someEntity);
  
      //Save in order to get the the id of the entity
      dbContext.SaveChanges();
  
      //Create related entity
      var relatedEntity = new RelatedEntity
      {
          SomeEntityId = someEntity.Id
      };
      dbContext.RelatedEntity.Add(relatedEntity)
      dbContext.SaveChanges();
      transaction.Commit();
  }
  </code></pre>
  
  <p>Here we need to Save the context in order to get the ID of an Entity which is related to another one we just have created.</p>
  
  <p>At the same time another service could update the same context. From what I have read, <code>DbContext</code> is not thread safe.</p>
  
  <p>Should I use <code>Transient</code> in this case? Why does the documentation suggest, I <strong>should</strong> use <code>Scoped</code>?</p>
  
  <p>Do I miss some important part of the framework?</p>