如何创建一个Quartz.NET的工作,需要注射autofac

时间:2023-03-10 06:22:11
如何创建一个Quartz.NET的工作,需要注射autofac

问题:

使用 Quartz.Net 做定时任务时,实现IJob对象的服务,Autofac不会自动注入,使用构造函数会直接出现异常,无法执行Execute方法。

解决方式

方法一: 使用 Autofac的Quartz.Net的扩展包

Gitbub地址:  https://github.com/alphacloud/Autofac.Extras.Quartz

 使用方法:

1、需要下载Autofac的扩展包,可以通过Nuget包管理工具下载
  Autofac.Extras.Quartz
2、在Autofac配置文件中注册Quartz模块
 //注册定时任务模块
builder.RegisterModule(new QuartzAutofacFactoryModule());
builder.RegisterModule(new QuartzAutofacJobsModule(typeof(JobTest).Assembly));
3、然后在Job任务对象中,就可以通过构造函数注入服务对象。
方法二:
因我本机的项目使用的Autofac是3.5版本,如果安装Autofac.Extras.Quartz,需要升级Autofac版本,要么用很旧的版本,方法一并不友好。
首先,在mvc根目录下新建Autofac扩展类:
   internal static  class AutofacExt
{
private static IContainer _container;
public static void InitAutofac()
{
var builder = new ContainerBuilder(); //注册数据库基础操作和工作单元
builder.RegisterGeneric(typeof(BaseRepository<>)).As(typeof(IRepository<>));
builder.RegisterType(typeof (UnitWork)).As(typeof (IUnitWork)); //注册WebConfig中的配置
builder.RegisterModule(new ConfigurationSettingsReader("autofac")); //注册app层
builder.RegisterAssemblyTypes(Assembly.GetAssembly(typeof (UserManagerApp))); //注册领域服务
builder.RegisterAssemblyTypes(Assembly.GetAssembly(typeof(AuthoriseService))); // Register your MVC controllers.
builder.RegisterControllers(typeof(MvcApplication).Assembly); // OPTIONAL: Register model binders that require DI.
builder.RegisterModelBinders(Assembly.GetExecutingAssembly());
builder.RegisterModelBinderProvider(); // OPTIONAL: Register web abstractions like HttpContextBase.
builder.RegisterModule<AutofacWebTypesModule>(); // OPTIONAL: Enable property injection in view pages.
builder.RegisterSource(new ViewRegistrationSource()); // OPTIONAL: Enable property injection into action filters.
builder.RegisterFilterProvider(); // Schedule
builder.Register(x => new StdSchedulerFactory().GetScheduler()).As<IScheduler>(); // Schedule jobs
builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).Where(x => typeof(IJob).IsAssignableFrom(x)); // Set the dependency resolver to be Autofac.
_container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(_container)); IScheduler sched = AutofacExt.GetFromFac<IScheduler>();
sched.JobFactory = new AutofacJobFactory(_container); IJobDetail job = JobBuilder.Create<TimeJob>()
.WithIdentity("job1", "group1")
.Build(); ITrigger trigger = TriggerBuilder.Create()
.WithIdentity("1JobTrigger")
.WithSimpleSchedule(x => x
.RepeatForever()
.WithIntervalInSeconds()
)
.StartNow()
.Build(); sched.ScheduleJob(job, trigger);
sched.Start();
} /// <summary>
/// 从容器中获取对象
/// </summary>
/// <typeparam name="T"></typeparam>
public static T GetFromFac<T>()
{
return _container.Resolve<T>();
}
}
    public class AutofacJobFactory : IJobFactory
{
private readonly IContainer _container;
public AutofacJobFactory(IContainer container)
{
_container = container;
}
public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler)
{
return (IJob)_container.Resolve(bundle.JobDetail.JobType);
} public void ReturnJob(IJob job)
{ }
}
[DisallowConcurrentExecution]
public class TimeJob : IJob
{
private LogManagerApp logManager;
public TimeJob()
{
logManager = AutofacExt.GetFromFac<LogManagerApp>();
}
public void Execute(IJobExecutionContext context)
{
//
}
}

TimeJob

在Application_Start()里添加这段代码即可:  AutofacExt.InitAutofac();