VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > temp > 简明python教程 >
  • Autofac依赖注入

复制代码
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>();
        }
    }
}
复制代码

相关教程