.net核心Quartz依赖注入

问题描述:

如何在 .net 内核中配置Quartz以使用依赖项注入?我使用标准的.net核心依赖机制。在实现 IJob 的类的构造函数中,我需要注入一些依赖项。

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.

Quartz.Spi.IJobFactory 接口并实现它。 Quartz文档指出:

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


触发触发器时,将通过在Scheduler上配置的JobFactory实例化与之关联的Job。默认的JobFactory仅激活作业类的新实例。您可能需要创建自己的JobFactory实现,以完成诸如使应用程序的IoC或DI容器生成/初始化作业实例之类的任务。
请参见IJobFactory接口和关联的Scheduler.SetJobFactory(fact)方法。

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;

编辑

实现看起来像这样:

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
    }
}

到将其与 Microsoft.Extensions.DependencyInjection 一起使用,即可创建容器:

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

var services = new ServiceCollection();
services.AddTransient<IAuthorizable, AuthorizeService>();
var container = services.BuildServiceProvider();
var jobFactory = new JobFactory(container);

参考文献


  1. Quartz文档

Api