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