c# - .net Core Quartz 依赖注入(inject)

标签 c# .net dependency-injection asp.net-core quartz.net

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

最佳答案

您可以使用Quartz.Spi.IJobFactory接口(interface)并实现它。 Quartz 文档指出:

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 一起使用,请像这样创建容器:

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

引用文献

  1. Quartz documentation

  2. Api

关于c# - .net Core Quartz 依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42157775/

相关文章:

c# - 将字符串拆分为无分隔符的数组

.net - 如何在后台线程运行时阻止Winforms UI

c# - 难看的文字问题

java - 从单元测试中注入(inject)模拟 Spring @Autowired 依赖项的最佳方法是什么?

javascript - 如何使用 C# 和 Angular js 在 View 上显示数据

c# - 不移动光标修改文本框

c# - 使用 Autofac 的 RegisterGeneric 注入(inject) NLog

.net - Rx 滑动窗口 - 适当的清理?

c# - 在没有第 3 方框架的情况下实现 DI

c# - 统一: Injection of multiple PerResolveLifetimeManager registered types