博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Autofac依赖注入

Posted on 2020-05-09 10:37  筑筑  阅读(313)  评论(0编辑  收藏  举报
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>();
        }
    }
}