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

Autofac依赖注入

程序员文章站 2022-07-09 19:23:57
using Autofac; using Autofac.Extras.Quartz; using Autofac.Integration.WebApi; using Quartz; using STAr.Enterprise.CRM.JobScheduler.Job; using System.C ......
using autofac;
using autofac.extras.quartz;
using autofac.integration.webapi;
using quartz;
using star.enterprise.crm.jobscheduler.job;
using system.collections.specialized;
using system.configuration;
using system.reflection;
using system.web.http;
namespace webapi
{
    public static class autofacconfig
    {

        private readonly static string _dicommonconfstring = configurationmanager.appsettings["dicommon"].trim();
        private readonly static string _direpositoryconfstring = configurationmanager.appsettings["direpository"].trim();
        private readonly static string _diservicesconfstring = configurationmanager.appsettings["diservices"].trim();
        private readonly static string _diintegrationconfstring = configurationmanager.appsettings["diintegration"].trim();
        private readonly static string _diauthorizationconfstring = configurationmanager.appsettings["diauthorization"].trim();
        

        public static ischeduler initautofacinit()
        {
            var builder = new containerbuilder();

            // configure and register quartz
            var schedulerconfig = new namevaluecollection { { "quartz.threadpool.threadcount", "10" }, { "quartz.scheduler.threadname", "scheduler" } };

            builder.registermodule(new quartzautofacfactorymodule
            {
                configurationprovider = c => schedulerconfig
            });
            builder.registermodule(new quartzautofacjobsmodule(typeof(testjob).assembly));
            //注册所有的apicontrollers
            builder.registerapicontrollers(assembly.getexecutingassembly()).propertiesautowired().instanceperlifetimescope();



            //注册所有的接口实现
            assembly dicommon = assembly.load(_dicommonconfstring);
            assembly direpository = assembly.load(_direpositoryconfstring);
            assembly diservices = assembly.load(_diservicesconfstring);
            assembly diintegration = assembly.load(_diintegrationconfstring);
            assembly diauthorization = assembly.load(_diauthorizationconfstring);

            builder.registerassemblytypes(dicommon, direpository, diservices, diintegration, diauthorization).asimplementedinterfaces();
            builder.registertypes(direpository.getexportedtypes()).propertiesautowired().instanceperlifetimescope();
            var container = builder.build();
            //注册api容器需要使用httpconfiguration对象
            httpconfiguration config = globalconfiguration.configuration;
            
            config.dependencyresolver = new autofacwebapidependencyresolver(container);

            // 依赖注入scheduler 并 返回
            return container.resolve<ischeduler>();
        }
    }
}