描述
我读了很多关于如何配置Autofac.Extras.Quartz以添加Autofac集成,但它根本不起作用,我很难解决这些问题:
我花了很多时间来弄清楚如何正确启动它(这看起来很简单,但在我的情况下却不可行),与我的案例closed issue最相关的是人们遇到同样问题,但是经历它没有帮助。 任何帮助表示赞赏。
代码:
...
// Configure Autofac
var builder = new ContainerBuilder();
...
builder.RegisterModule<AutofacRepositoryModule>(); // registration of repositores
...
builder.RegisterModule(new QuartzAutofacFactoryModule());
builder.RegisterModule(new QuartzAutofacJobsModule(typeof(ConvertOrdersJob).Assembly));
builder.RegisterType<JobScheduler>().AsSelf();
var container = builder.Build();
ConfigureScheduler(container);
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
...
private static void ConfigureScheduler(IContainer container)
{
var scheduler = container.Resolve<JobScheduler>();
scheduler.Start();
}
在AutofacRepositoryModule中注册存储库:
public class AutofacRepositoryModule : Module
{
protected override void Load(ContainerBuilder builder)
{
...
builder.RegisterType<DumpReportRepository>().As<IDumpReportRepository>();
...
}
}
配置工作:
public class JobScheduler
{
private IScheduler _scheduler;
public JobScheduler(IScheduler scheduler)
{
_scheduler = scheduler;
}
public void Start()
{
// BUG1: Find out why cleanupDumpsTrigger never fired
// BUG2: Dependency injection via constructor does not work
var cleanupDumpsJob = JobBuilder.Create<DumpsCleanupJob>().Build();
var cleanupDumpsTrigger = TriggerBuilder.Create()
.WithIdentity("CleanupDumpsTrigger", "dumps")
.StartNow()
.WithSimpleSchedule(x => x
.WithIntervalInHours(24)
.RepeatForever())
.Build();
_scheduler.ScheduleJob(cleanupDumpsJob, cleanupDumpsTrigger);
var convertOrdersJob = JobBuilder.Create<ConvertOrdersJob>().Build();
var convertOrdersTrigger = TriggerBuilder.Create()
.WithIdentity("ConvertOrdersTrigger", "orders")
.StartNow()
.WithSimpleSchedule(x => x
.WithIntervalInHours(1)
.RepeatForever())
.Build();
_scheduler.ScheduleJob(convertOrdersJob, convertOrdersTrigger);
_scheduler.Start();
}
工作示例:
[DisallowConcurrentExecution]
public class DumpsCleanupJob : IJob
{
private readonly IDumpReportRepository _dumpReportRepository;
public DumpsCleanupJob(IDumpReportRepository dumpReportRepository)
{
// BUG: Constructor is never called
_dumpReportRepository = dumpReportRepository;
}
public void Execute(IJobExecutionContext context)
{
try
{
...
}
catch (Exception ex)
{
...
}
}
}
版本:
我尝试了一系列版本的Quartz(2.x-3.x)/Autofac.Extras.Quartz(3.x-4.0.0)
解决方法
临时解决方案:
_scheduler = StdSchedulerFactory.GetDefaultScheduler()
配置所有作业(所有作业都正确启动)如果包不起作用,则将实现自定义AutofacJobFactory。
答案 0 :(得分:0)
您可以尝试使用自定义IJobFactory创建作业。
scheduler.JobFactory = new JobFactoryInjection(container);