我在使用流畅的调度程序或其他同步功能时遇到了同样的问题。为此,我创建了一个ServiceScopeFactory
对象并将其注入注册表的构造函数中。
我在 startup.cs 的 Configure() 函数中初始化了我的作业管理器-
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
IServiceScopeFactory serviceScopeFactory = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>();
JobManager.Initialize(new SchedulerRegistry(serviceScopeFactory));
}
调度程序注册表 -
public SchedulerRegistry(IServiceScopeFactory serviceScopeFactory)
{
Schedule(() => new SyncUpJob(serviceScopeFactory)).ToRunNow().AndEvery(1).Months().OnTheFirst(DayOfWeek.Monday).At(3, 0);
}
SyncupJob -
public class SyncUpJob : IJob
{
/// <summary>
///
/// </summary>
/// <param name="migrationBusiness"></param>
public SyncUpJob (IServiceScopeFactory serviceScopeFactory)
{
this.serviceScopeFactory = serviceScopeFactory;
}
private IServiceScopeFactory serviceScopeFactory;
/// <summary>
///
/// </summary>
public void Execute()
{
// call the method to run weekly
using (var serviceScope = serviceScopeFactory.CreateScope())
{
IMigrationBusiness migrationBusiness = serviceScope.ServiceProvider.GetService<IMigrationBusiness>();
migrationBusiness.SyncWithMasterData();
}
}
}