问题:

使用 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();

最新文章

  1. SQL Server常用的性能诊断语句
  2. Windows上Python2.7安装Scrapy过程
  3. 表单form的属性,单行文本框、密码框、单选多选按钮
  4. 【转】ubuntu 编码 UTF-8 GBK GB18030
  5. [Doc ID 1590988.1]如何清理E-Business Suite的缓存(Apache/iAS, Cabo, Modplsql, Browser, Jinitiator, Java, Portal, WebADI)?
  6. OPENSHIFT MYSQL使用Navicat连接配置
  7. 将图片转换为Base64
  8. SVN 一次性提交多个目录中文件
  9. GridView出现不完整--GridView删除滚动条
  10. 全栈project师的毁与誉
  11. php利用gd实现图片的边框
  12. vscode前端常用插件推荐,搭建JQuery、Vue等开发环境
  13. 「2017 山东三轮集训 Day1」Flair
  14. oracle 日期取 月 日
  15. 转载:Nginx是什么(1.1)《深入理解Nginx》(陶辉)
  16. mysql语句判断是否存在记录,没有则插入新纪录否则不执行
  17. flash初步尝试
  18. 第三百九十九节,Django+Xadmin打造上线标准的在线教育平台—生产环境部署CentOS6.5安装mysql5.6
  19. 手机调试 fiddler
  20. VSFTPD虚拟用户配置

热门文章

  1. linux下c的网络编程---转载
  2. 关于around_filter 的调用
  3. Fiddler实现手机抓包——小白入门(转载csdn)
  4. Golang cron 定时任务使用
  5. ABP学习入门系列(四)(创建Service)
  6. PHP错误日志和内存查看
  7. SpringBoot配置文件注入值数据校验
  8. SpringMVC入门(二)—— 参数的传递、Controller方法返回值、json数据交互、异常处理、图片上传、拦截器
  9. Ubuntu使用心得
  10. Algorithm——两个排序数组的中位数