一、nuget下载相关类库引用
install-package Quartz
install-package Autofac
install-package Autofac.Configuration
install-package Autofac.Extras.Quartz
二、配置autofac注入
public class AutofacUtil { /// <summary> /// Autofac容器对象 /// </summary> private static IContainer _container; /// <summary> /// 初始化autofac /// </summary> public static void InitAutofac() { var builder = new ContainerBuilder(); //配置接口依赖 builder.RegisterInstance<IDbConnection>(DBFactory.CreateConnection()).As<IDbConnection>(); builder.RegisterGeneric(typeof(GenericRepository<>)).As(typeof(IGenericRepository<>)); //注入仓储类 builder.RegisterAssemblyTypes(Assembly.Load("Demo.Repository")) .Where(x => x.Name.EndsWith("Repository")) .AsImplementedInterfaces(); //配置quartz.net依赖注入 builder.RegisterModule(new QuartzAutofacFactoryModule()); builder.RegisterModule(new QuartzAutofacJobsModule(Assembly.GetExecutingAssembly())); _container = builder.Build(); } /// <summary> /// 从Autofac容器获取对象 /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public static T GetFromFac<T>() { return _container.Resolve<T>(); } }
三、windows服务注入autofac
static class Program { /// <summary> /// 应用程序的主入口点。 /// </summary> static void Main() { //windows服务初始化工作 AutofacUtil.InitAutofac(); ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] { new Service1() }; ServiceBase.Run(ServicesToRun); } }
四、quartz任务中注入服务
/// <summary> /// 推送短信任务 /// </summary> public class PushSMSJob : IJob { private readonly ISMSNoticeRepository _smsNoticeRepository; public PushSMSJob(ISMSNoticeRepository smsNoticeRepository) { _smsNoticeRepository = smsNoticeRepository; } /// <summary> /// 执行推送短信的具体实现代码 /// </summary> /// <param name="context"></param> public void Execute(IJobExecutionContext context) { //获取待发送短信列表 var waitSendList = _smsNoticeRepository.GetWaitForSendSMS(); } }