作者:WO | 来源:互联网 | 2023-02-03 15:40
我在.NET Core Web应用程序的Startup类中安装并配置了Hangfire,如下所示(删除了很多非Hangfire代码):
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseHangfireServer();
//app.UseHangfireDashboard();
//RecurringJob.AddOrUpdate(() => DailyJob(), Cron.Daily);
}
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddOptions();
services.Configure(Configuration);
services.AddSingleton(Configuration);
services.AddSingleton();
services.AddScoped((sp) => sp.GetService().HttpContext.User);
services.AddScoped();
services.AddHangfire(x => 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();
scheduledTaskManager.ProcessDailyJob();
}
}
private IContainer getJobContainer()
{
var builder = new ContainerBuilder();
builder.RegisterModule(new BusinessBindingsModule());
builder.RegisterModule(new DataAccessBindingsModule());
return builder.Build();
}
}
如您所见,我正在使用Autofac进行DI.每次Hangfire作业执行时,我都会设置注入新容器.
目前,我有UseHangfireDashboard()
一个调用添加我的定期作业注释,我在行参考时收到以下错误IPrincipal
:
System.NullReferenceException:'对象引用未设置为对象的实例.'
我知道Hangfire没有HttpContext
.我不确定为什么它甚至会为Hangfire线程启动那行代码.我最终需要为我的IPrincipal依赖解析服务帐户.
如何解决Hangfire和HttpContext的问题?