.net Core Quartz Dependency Injection

匿名 (未验证) 提交于 2019-12-03 02:03:01

问题:

How can I configure Quartz in .net core to use dependency injection? I using standard .net core Dependency mechanism. In constructor of class that implements IJob, I need inject some dependencies.

回答1:

You can use the Quartz.Spi.IJobFactory interface and implement it. The Quartz documentations states:

When a trigger fires, the Job it is associated to is instantiated via the JobFactory configured on the Scheduler. The default JobFactory simply activates a new instance of the job class. You may want to create your own implementation of JobFactory to accomplish things such as having your application’s IoC or DI container produce/initialize the job instance. See the IJobFactory interface, and the associated Scheduler.SetJobFactory(fact) method.

ISchedulerFactory schedulerFactory = new StdSchedulerFactory(properties); var scheduler = schedulerFactory.GetScheduler();  scheduler.JobFactory = jobFactory; 

Edit

The implementation can look like this:

public class JobFactory : IJobFactory {     protected readonly IServiceProvider Container;      public JobFactory(IServiceProvider container)     {         Container = container;     }      public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler)     {         return Container.GetService(bundle.JobDetail.JobType) as IJob;     }      public void ReturnJob(IJob job)     {         // i couldn't find a way to release services with your preferred DI,          // its up to you to google such things     } } 

To use it with the Microsoft.Extensions.DependencyInjection create your container like this:

var services = new ServiceCollection(); services.AddTransient(); var container = services.BuildServiceProvider(); var jobFactory = new JobFactory(container); 

References

  1. Quartz documentation

  2. Api



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