.net Core Quartz 依赖注入 [英] .net Core Quartz Dependency Injection

查看:103
本文介绍了.net Core 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:

当触发器触发时,它关联的作业通过在调度程序上配置的 JobFactory 实例化.默认的 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

这篇关于.net Core Quartz 依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆