一:問題場景
在一次專案開發中,專案中已使用了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);
}
}