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);
}
}