How do I create a Quartz.NET’s job requiring injection with autofac

旧城冷巷雨未停 提交于 2019-12-03 06:12:49

I finally tracked down what the issue was.

My release service was using a data repository which was being created with a different scope.

I discovered this by creating a new test service that did nothing but return a string, and that worked being injected into a quartz job.

On discovering this, I changed the scope of the repository called upon by the release service , and then the release service started working inside the quartz job.

My apologies to anyone that looked at this question to try and help me out. Because the code of the release service was not listed, it would have been difficult to figure out what was wrong.

I have updated the code with the final working bindings I used for quartz with autofac.

The problem is that your AutofacJobFactory is not creating the ReleaseJob (you are doing this with JobBuilder.Create<ReleaseJob>() instead), so the IoC container is not aware of it's instantiation meaning dependency injection cannot occur.

The following code should work:

sched = schedFact.GetScheduler();
sched.JobFactory = new AutofacJobFactory(container);
sched.Start();

// construct job info
JobDetailImpl jobDetail = new JobDetailImpl("1Job", null, typeof(ReleaseJob ));

ITrigger trigger = TriggerBuilder.Create()
    .WithIdentity("1JobTrigger")
    .WithSimpleSchedule(x => x
        .RepeatForever()
        .WithIntervalInSeconds(5)
    )
    .StartNow()
    .Build();

sched.ScheduleJob(jobDetail, trigger);

Note that in this example we are not using JobBuilder.Create<ReleaseJob>() anymore, instead we pass the details of the job to be created via the JobDetailImpl object and by doing this the scheduler's jobfactory (the AutofacJobFactory) is responsible for instantiating the job and Dependency injection can occur.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!