title: Resolving Hangfire dependencies/HttpContext in .NET Core Startup
body: <p>I've installed and configured Hangfire in my .NET Core web application's Startup class as follows (with a lot of the non-Hangfire code removed):</p>
  
  <pre><code>public class Startup
  {
      public void Configuration(IAppBuilder app)
      {
          app.UseHangfireServer();
          //app.UseHangfireDashboard();
          //RecurringJob.AddOrUpdate(() =&gt; DailyJob(), Cron.Daily);
      }
  
      public IServiceProvider ConfigureServices(IServiceCollection services)
      {
          services.AddOptions();
          services.Configure&lt;AppSettings&gt;(Configuration);
          services.AddSingleton&lt;IConfiguration&gt;(Configuration);
          services.AddSingleton&lt;IHttpContextAccessor, HttpContextAccessor&gt;();
          services.AddScoped&lt;IPrincipal&gt;((sp) =&gt; sp.GetService&lt;IHttpContextAccessor&gt;().HttpContext.User);
          services.AddScoped&lt;IScheduledTaskService, ScheduledTaskService&gt;();
  
          services.AddHangfire(x =&gt; x.UseSqlServerStorage(connectionString));    
          this.ApplicationContainer = getWebAppContainer(services);
          return new AutofacServiceProvider(this.ApplicationContainer);
      }
  }
  
  public interface IScheduledTaskService
  {
      void OverduePlasmidOrdersTask();
  }
  
  public class ScheduledTaskService : IScheduledTaskService
  {
      public void DailyJob()
      {
          var container = getJobContainer();
          using (var scope = container.BeginLifetimeScope())
          {
              IScheduledTaskManager scheduledTaskManager = scope.Resolve&lt;IScheduledTaskManager&gt;();
              scheduledTaskManager.ProcessDailyJob();
          }
      }
  
      private IContainer getJobContainer()
      {
          var builder = new ContainerBuilder();
          builder.RegisterModule(new BusinessBindingsModule());
          builder.RegisterModule(new DataAccessBindingsModule());
          return builder.Build();
      }
  }
  </code></pre>
  
  <p>As you can see, I'm using Autofac for DI.  I've set things up to inject a new container each time the Hangfire job executes.</p>
  
  <p>Currently, I have <code>UseHangfireDashboard()</code> as well as the call to add my recurring job commented out and I'm receiving the following error on the line referencing <code>IPrincipal</code>:</p>
  
  <blockquote>
    <p>System.NullReferenceException: 'Object reference not set to an instance of an object.'</p>
  </blockquote>
  
  <p>I understand that Hangfire does not have an <code>HttpContext</code>.  I'm not really sure why it's even firing that line of code for the Hangfire thread.  I'm ultimately going to need to resolve a service account for my IPrincipal dependency.  </p>
  
  <p>How can I address my issue with Hangfire and HttpContext? </p>