Files
HTCloud/HT.Cloud.Service/AutoJob/IOCJobFactory.cs
2023-03-03 16:07:50 +08:00

32 lines
1020 B
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using Microsoft.Extensions.DependencyInjection;
using Quartz;
using Quartz.Spi;
using System;
namespace HT.Cloud.Service.AutoJob
{
/// <summary>
/// 依赖注入必须代替原本的SimpleJobFactory
/// </summary>
public class IOCJobFactory : IJobFactory
{
private readonly IServiceProvider _serviceProvider;
public IOCJobFactory(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler)
{
var serviceScope = _serviceProvider.CreateScope(); // 获得一个ioc对象指定创建scope级别的实例在job里面需要依赖注入ef但是startup里面配置的ef是scope级别的必须指定为scope不然报错。不写的话默认是单例。
return serviceScope.ServiceProvider.GetService(bundle.JobDetail.JobType) as IJob; // 依赖注入一个 job 然后返回
}
public void ReturnJob(IJob job)
{
var disposable = job as IDisposable;
disposable?.Dispose();
}
}
}