title: How to get user information in DbContext using Net Core
body: <p>I am trying to develop a class library in which i want to implement custom <code>DbContext</code>. In the <code>SaveChanges</code> method of the <code>DbContext</code>, i need to get current user’s information(department, username etc.) for auditing purpose. Some part of the <code>DbContext</code> code is below:</p>
  
  <pre><code>public override int SaveChanges()
  {
      // find all changed entities which is ICreateAuditedEntity 
      var addedAuditedEntities = ChangeTracker.Entries&lt;ICreateAuditedEntity&gt;()
             .Where(p =&gt; p.State == EntityState.Added)
             .Select(p =&gt; p.Entity);
  
      var now = DateTime.Now;
  
      foreach (var added in addedAuditedEntities)
      {
          added.CreatedAt = now;
          added.CreatedBy = ?;
          added.CreatedByDepartment = ?
      }
      return base.SaveChanges();
  }
  </code></pre>
  
  <p>Two options coming to mind:</p>
  
  <ul>
  <li>Using <code>HttpContext.Items</code> to keep user information, injecting IHttpContextAccessor and getting information from the
  <code>HttpContext.Items</code>(In this case <code>DbContext</code> depends <code>HttpContext</code>, is it
  correct?)</li>
  <li>Using ThreadStatic object instead of <code>HttpContext.Items</code> and getting information from the object( I read some posts
  that ThreadStatic is not safe)</li>
  </ul>
  
  <p><strong>Question</strong> : Which is the best fit into my case? Is there another way you suggest?</p>