如何集成需要向其中注入“范围”服务的Quartz.Net作业(ASP.NET Core 2.0)?

时间:2019-03-14 18:56:44

标签: asp.net-core asp.net-core-2.0 quartz.net

我正在尝试从my own answer开始this question之后创建一些Quartz.Net作业。但是,如果作业非常复杂并且需要“作用域”(services.AddScoped<.., ...>)服务,则该示例将无法正常工作,因为作业是作为单例创建的。

如果将它们更改为范围,则serviceProvider不包含我需要的服务。我设法使用以下代码使其工作:

Startup.cs

/// <summary>
/// service provider to be used by qiaryz job factory which cannot use its default provider
/// since child services are scoped and the jobs are singleton
/// </summary>
public static IServiceProvider QuartzScopedProvider { get; private set; }

private void ConfigureQuartz(IServiceCollection services, params Type[] jobs)
{
    services.AddSingleton<IJobFactory, QuartzJobFactory>();
    services.Add(jobs.Select(jobType => new ServiceDescriptor(jobType, jobType, ServiceLifetime.Singleton)));

    QuartzScopedProvider = services.BuildServiceProvider();

    services.AddSingleton(provider =>
    {
        var schedulerFactory = new StdSchedulerFactory();
        var scheduler = schedulerFactory.GetScheduler().Result;
        scheduler.JobFactory = provider.GetService<IJobFactory>();
        scheduler.Start();
        return scheduler;
    });
}

/// <summary>
/// configures quartz services
/// </summary>
/// <param name="services"></param>
protected virtual void ConfigureJobsIoc(IServiceCollection services)
{
    // all custom services are already defined at this point

    ConfigureQuartz(services, typeof(ComplexJob));
}

/// <summary>
/// configures and starts async jobs (Quartz)
/// </summary>
/// <param name="app"></param>
/// <param name="lifetime"></param>
protected virtual void StartJobs(IApplicationBuilder app, IApplicationLifetime lifetime)
{
    var scheduler = app.ApplicationServices.GetService<IScheduler>();

    QuartzServicesUtilities.StartJob<ComplexJob>(scheduler, TimeSpan.FromMinutes(60));

    lifetime.ApplicationStarted.Register(() => scheduler.Start());
    lifetime.ApplicationStopping.Register(() => scheduler.Shutdown(waitForJobsToComplete: true));
}

QuartzJobFactory.cs

作业工厂不使用注入的服务提供程序,而是在Startup.cs中显式构建的服务提供程序。

public class QuartzJobFactory : IJobFactory
{
    private readonly IServiceProvider _serviceProvider;

    /// <inheritdoc/>
    public QuartzJobFactory()
    {
        // _serviceProvider = serviceProvider;
        _serviceProvider = Startup.QuartzScopedProvider;
    }

    /// <inheritdoc/>
    public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler)
    {
        var jobDetail = bundle.JobDetail;

        // this fails with injected service provider:
        // 1: cannot inject scoped services in singleton service
        // 2: if jobs are scoped, the provider cannot solve the injected services
        var job = (IJob)_serviceProvider.GetService(jobDetail.JobType);
        return job;
    }

    /// <inheritdoc/>
    public void ReturnJob(IJob job) { }
}

我想知道这是否是在ASP.NET Core 2.0中处理Quartz作业的好方法,因为它看起来更像是黑客,而不是真正的解决方案。

问题::如何集成需要向其中注入“范围”服务(ASP.NET Core 2.0)的Quartz.Net作业?

2 个答案:

答案 0 :(得分:1)

要从IServiceProvider保护作用域服务,请尝试

    using (var scope = _serviceProvider.CreateScope())
    {
        var job = (IJob)scope.ServiceProvider.GetService(jobDetail.JobType);            
    }

答案 1 :(得分:1)

从Quartz 3.1开始,无需创建自定义JobFactory(或JobRunner)即可使用范围服务。我们可以使用内置作业工厂,为我们创建范围:

services.AddQuartz(q =>  
{                   
    q.UseMicrosoftDependencyInjectionScopedJobFactory();
});

来自docs。 在后台,MicrosoftDependencyInjectionJobFactory在作业执行之前创建范围,并使用包装器ScopedJob在范围内运行目标作业。