title: Access HttpContextAccessor from startup.cs in .net Core WebApi
body: <p>I'm logging exceptions to database in asp.net core. MyDbContext take HttpContextAccessor parameter.So, I'm sending HttpContextAccessor to MyDbContext.cs for access my JWT. But, I can't access my HttpContextAccessor from Startup.cs. How can I achieve this?</p>
  
  <p>Startup.cs</p>
  
  <pre><code>   public void ConfigureServices(IServiceCollection services)
      {
          services.AddHttpContextAccessor();
          services.AddMvc();
          services.AddSingleton&lt;IHttpContextAccessor, HttpContextAccessor&gt;();
          services.AddDbContext&lt;MyDbContext&gt;();
          services.AddTransient&lt;IUnitOfWork, UnitOfWork&gt;();
      }
  
  
      public void Configure(IApplicationBuilder app, IHostingEnvironment env)
      {
           app.UseExceptionHandler(builder =&gt; builder.Run(async context =&gt;
           {
               var error = context.Features.Get&lt;IExceptionHandlerFeature&gt;();
  
               context.Response.AddApplicationError(error,???????);//I want access HttpContextAccessor
               await context.Response.WriteAsync(error.Error.Message);
           }));
  
          app.UseHttpsRedirection();
          app.UseMvc();
      }
  </code></pre>
  
  <p>ExceptionHelper.cs</p>
  
  <pre><code> public static class ExceptionHelper
      {
          public static async Task AddApplicationError(this HttpResponse response, IExceptionHandlerFeature error, IHttpContextAccessor httpContextAccessor)
          {
             Log log = new Log();
             log.Message = error.Error.Message;          
  
             MyDbContext context = new MyDbContext(null, httpContextAccessor);
             UnitOfWork uow = new UnitOfWork(context);
             uow.LogRepo.AddOrUpdate(log);
             await uow.CompleteAsync(false);               
          }
      }
  </code></pre>
  
  <p>MyDbContext</p>
  
  <pre><code>public class MyDbContext : DbContext
  {
      private readonly IHttpContextAccessor _httpContextAccessor;
  
      public MyDbContext(DbContextOptions&lt;MyDbContext&gt; options, IHttpContextAccessor httpContextAccessor)
          : base(GetOptions())
      {
          _httpContextAccessor = httpContextAccessor;
      }
  
      private static DbContextOptions GetOptions()
      {
          return SqlServerDbContextOptionsExtensions.UseSqlServer(new DbContextOptionsBuilder(), "server=asd; database=; user id=asd; password=1234").Options;
      }
  
      public override async Task&lt;int&gt; SaveChangesAsync(CancellationToken cancellationToken = default(CancellationToken))
      {
          var token = _httpContextAccessor.HttpContext.Request.Headers["Authorization"];
          var audits = AuditHelper.AddAuditLog(base.ChangeTracker, token);
          return (await base.SaveChangesAsync(true, cancellationToken));
      }
  }
  </code></pre>