簡體   English   中英

Quartz.Net 依賴注入 .Net Core

[英]Quartz.Net Dependency Injection .Net Core

在我的項目中,我必須使用 Quartz,但我不知道我做錯了什么。

工作工廠:

public class IoCJobFactory : IJobFactory
{
    private readonly IServiceProvider _factory;

    public IoCJobFactory(IServiceProvider factory)
    {
        _factory = factory;
    }
    public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler)
    {
        return _factory.GetService(bundle.JobDetail.JobType) as IJob;
    }

    public void ReturnJob(IJob job)
    {
        var disposable = job as IDisposable;
        if (disposable != null)
        {
            disposable.Dispose();
        }
    }
}

石英擴展:

public static class QuartzExtensions
{
    public static void UseQuartz(this IApplicationBuilder app)
    {
        app.ApplicationServices.GetService<IScheduler>();
    }

    public static async void AddQuartz(this IServiceCollection services)
    {
        var props = new NameValueCollection
        {
            {"quartz.serializer.type", "json"}
        };
        var factory = new StdSchedulerFactory(props);
        var scheduler = await factory.GetScheduler();

        var jobFactory = new IoCJobFactory(services.BuildServiceProvider());
        scheduler.JobFactory = jobFactory;
        await scheduler.Start();
        services.AddSingleton(scheduler);
    }
}

當我嘗試運行我的工作(類有依賴注入)時,我總是得到異常,因為:

_factory.GetService(bundle.JobDetail.JobType) as IJob;

始終為空。

我的班級實現IJob並在 startup.cs 中添加:

services.AddScoped<IJob, HelloJob>();
services.AddQuartz();

app.UseQuartz();

我使用標准的 .net Core 依賴注入:

using Microsoft.Extensions.DependencyInjection;

這只是我解決 IoC 問題的解決方案的一個簡單示例:

作業工廠.cs

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)
        {
            (job as IDisposable)?.Dispose();
        }
    }

啟動文件

public void Configure(IApplicationBuilder app, 
            IHostingEnvironment env, 
            ILoggerFactory loggerFactory,
            IApplicationLifetime lifetime,
            IServiceProvider container)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseMvc();

            // the following 3 lines hook QuartzStartup into web host lifecycle
            var quartz = new QuartzStartup(container);
            lifetime.ApplicationStarted.Register(quartz.Start);
            lifetime.ApplicationStopping.Register(quartz.Stop);
        }

QuartzStartup.cs

public class QuartzStartup
    {
        private IScheduler _scheduler; // after Start, and until shutdown completes, references the scheduler object
        private readonly IServiceProvider container;

        public QuartzStartup(IServiceProvider container)
        {
            this.container = container;
        }

        // starts the scheduler, defines the jobs and the triggers
        public void Start()
        {
            if (_scheduler != null)
            {
                throw new InvalidOperationException("Already started.");
            }

            var schedulerFactory = new StdSchedulerFactory();
            _scheduler = schedulerFactory.GetScheduler().Result;
            _scheduler.JobFactory = new JobFactory(container);
            _scheduler.Start().Wait();

            var voteJob = JobBuilder.Create<VoteJob>()
                .Build();

            var voteJobTrigger = TriggerBuilder.Create()
                .StartNow()
                .WithSimpleSchedule(s => s
                    .WithIntervalInSeconds(60)
                    .RepeatForever())
                .Build();

            _scheduler.ScheduleJob(voteJob, voteJobTrigger).Wait();
        }

        // initiates shutdown of the scheduler, and waits until jobs exit gracefully (within allotted timeout)
        public void Stop()
        {
            if (_scheduler == null)
            {
                return;
            }

            // give running jobs 30 sec (for example) to stop gracefully
            if (_scheduler.Shutdown(waitForJobsToComplete: true).Wait(30000))
            {
                _scheduler = null;
            }
            else
            {
                // jobs didn't exit in timely fashion - log a warning...
            }
        }
    }  

考慮您應該提前將您的服務注冊到容器中(在我的例子中是 VoteJob)。
我根據這個答案實現了這個。
我希望它會有所幫助。

我遇到了同樣的問題。

我更新自

services.AddScoped<IJob, HelloJob>();

services.AddScoped<HelloJob>();

那么它的工作原理。

_factory.GetService(bundle.JobDetail.JobType) as IJob; 不會為空 :)

這就是我在我的應用程序中所做的。 我只添加工廠,而不是將調度程序添加到 ioc

services.AddTransient<IJobFactory, AspJobFactory>(
                (provider) =>
                {
                    return new AspJobFactory( provider );
                } );

我的工作工廠看起來幾乎一樣。 瞬態並不重要,因為無論如何我只使用一次。 我使用 Quartz 擴展方法然后是

public static void UseQuartz(this IApplicationBuilder app, Action<Quartz> configuration)
        {
            // Job Factory through IOC container
            var jobFactory = (IJobFactory)app.ApplicationServices.GetService( typeof( IJobFactory ) );
            // Set job factory
            Quartz.Instance.UseJobFactory( jobFactory );

            // Run configuration
            configuration.Invoke( Quartz.Instance );
            // Run Quartz
            Quartz.Start();
        }

Quartz類也是 Singleton。

Quartz.NET 3.1 將包括對 Microsoft DI 和 ASP.NET Core 托管服務的官方支持。

您可以找到重新訪問的軟件包:

查看正在進行的新 DI 集成的最佳資源是前往示例 ASP.NET Core 應用程序

https://www.quartz-scheduler.net/2020/07/08/quartznet-3-1-beta-1-released/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM