Autofac 和 Quartz.Net 自动注入的整合

一:问题场景

在一次项目开发中,项目中已使用了Autofac.在新需求中要用到Quatrz.Net.在任务中使用注入方法,确始终无法使用注入的方法,经过千百次的度娘,终于找到了解决办法!吐槽下度娘真心不好用~~~

二:解决问题

1:需要下载Autofac的扩展包

https://github.com/alphacloud/Autofac.Extras.Quartz

或者

Nuget: install-package Autofac.Extras.Quartz

2:在Autofac配置文件中注册Quartz模块并实现Quatrz

var builder = new ContainerBuilder();

builder.RegisterControllers(typeof(MvcApplication).Assembly);
builder.RegisterType<QuartzServer>().As<IQuartzServer>().InstancePerLifetimeScope();
builder.RegisterModule(new QuartzAutofacFactoryModule());
builder.RegisterModule(new QuartzAutofacJobsModule(typeof(JobTest).Assembly));

var _container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(_container));

var scheduler = _container.Resolve<IScheduler>();
scheduler.Start();
IJobDetail job = JobBuilder.Create<JobTest>().Build();
ITrigger trigger = TriggerBuilder.Create()
     .WithSimpleSchedule(t =>
      t.WithIntervalInSeconds(5)
      .RepeatForever())
      .Build();
scheduler.ScheduleJob(job, trigger);

3:实现定时任务

public class JobTest : IJob
    {

//这里我们就可以使用构造函数注入容器了
        private IQuartzServer _quartzServer;
        public JobTest(IQuartzServer quartzServer)
        {
            _quartzServer = quartzServer;
        }
        public void Execute(IJobExecutionContext context)
        {
            var reportDirectory = string.Format("~/reports/{0}/", DateTime.Now.ToString("yyyy-MM"));
            reportDirectory = System.Web.Hosting.HostingEnvironment.MapPath(reportDirectory);
            if (!Directory.Exists(reportDirectory))
            {
                Directory.CreateDirectory(reportDirectory);
            }
            var dailyReportFullPath = string.Format("{0}report_{1}.log", reportDirectory, DateTime.Now.Day);
            var logContent = string.Format("{0}=>{1}{2}", DateTime.Now, "Create New Log."+this._quartzServer.Log(), Environment.NewLine);
            File.AppendAllText(dailyReportFullPath, logContent);
        }
    }

上一篇:css div inline 与 span 区别


下一篇:linux系统编程:IO读写过程的原子性操作实验