windows服务autofac注入quartz任务

一、nuget下载相关类库引用

  install-package Quartz

      install-package Autofac

  install-package Autofac.Configuration

      install-package Autofac.Extras.Quartz

 

二、配置autofac注入

public class AutofacUtil
    {
        /// 
        /// Autofac容器对象
        /// 
        private static IContainer _container;

        /// 
        /// 初始化autofac
        /// 
        public static void InitAutofac()
        {
            var builder = new ContainerBuilder();

            //配置接口依赖
            builder.RegisterInstance(DBFactory.CreateConnection()).As();
            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();
        }

        /// 
        /// 从Autofac容器获取对象
        /// 
        /// 
        /// 
        public static T GetFromFac()
        {
            return _container.Resolve();
        }
    }

 

三、windows服务注入autofac

    static class Program
    {
        /// 
        /// 应用程序的主入口点。
        /// 
        static void Main()
        {
            //windows服务初始化工作
            AutofacUtil.InitAutofac();

            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[] 
            { 
                new Service1() 
            };
            ServiceBase.Run(ServicesToRun);
        }
    }

 

四、quartz任务中注入服务

 /// 
    /// 推送短信任务
    /// 
    public class PushSMSJob : IJob
    {
        private readonly ISMSNoticeRepository _smsNoticeRepository;

        public PushSMSJob(ISMSNoticeRepository smsNoticeRepository)
        {
            _smsNoticeRepository = smsNoticeRepository;
        }

        /// 
        /// 执行推送短信的具体实现代码
        /// 
        /// 
        public void Execute(IJobExecutionContext context)
        {
            //获取待发送短信列表
            var waitSendList = _smsNoticeRepository.GetWaitForSendSMS();
        }
    }

 

你可能感兴趣的:(windows服务autofac注入quartz任务)