欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

windows服务autofac注入quartz任务

程序员文章站 2022-06-19 17:10:29
一、nuget下载相关类库引用 install-package Quartz install-package Autofac install-package Autofac.Configuration install-package Autofac.Extras.Quartz 二、配置autofac ......

一、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();
        }
    }