Autofac 依赖注入

在Global.asax.cs 里注册

   protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);

            SetKeywordInCache();
            AutoMapperConfiguration.Configure();
            Gxrc.Model.Mappings.AutoMapperConfiguration.Configure();
            Bootstrapper.Run(); //启动注册
            //Gxrc.BLL.Helper.WLXTSettingHelp.InitWLXTSettinList();
        }
using System.Web.Mvc;
using Autofac;
using Autofac.Integration.Mvc;
using System.Reflection;
using Gxrc.DATA;
using Gxrc.Model.Mappings;
using Gxrc.DATA.DataOperation.Other;
using Gxrc.Service.Other;
using Gxrc.Service.Other.Setting;

namespace Mvc_Vip
{
    public static class Bootstrapper
    {
        public static void Run()
        {
            SetAutofacContainer();
            AutoMapperConfiguration.Configure();
        }
        private static void SetAutofacContainer()
        {
            ContainerBuilder builder = new ContainerBuilder();
            builder.RegisterControllers(Assembly.GetExecutingAssembly());
            builder.RegisterType<UnitOfWork>().As<IUnitOfWork>().InstancePerRequest();
            builder.RegisterFilterProvider();
            builder.RegisterType<EnterpriseDatabaseFactory>().As<IEnterpriseDatabaseFactory>().InstancePerRequest();
            builder.RegisterType<LogDatabaseFactory>().As<ILogDatabaseFactory>().InstancePerRequest();
            builder.RegisterType<OtherDatabaseFactory>().As<IOtherDatabaseFactory>().InstancePerRequest();
            builder.RegisterType<JobseekerDatabaseFactory>().As<IJobseekerDatabaseFactory>().InstancePerRequest();
            builder.RegisterType<TimelineDatabaseFactory>().As<ITimelineDatabaseFactory>().InstancePerRequest();


            builder.RegisterAssemblyTypes(typeof(WLXTSettingOperation).Assembly)
           .Where(t => t.Name.EndsWith("Operation"))
           .AsSelf().InstancePerRequest();
            builder.RegisterAssemblyTypes(typeof(WLXTSettingService).Assembly)
            .Where(t => t.Name.EndsWith("Service"))
           .AsSelf().InstancePerRequest(); //service 所在程序集dll 所有以Service结尾的都注册。

            var container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }

        #region Bll层 非接口抽象类注入
        /// <summary>
        /// 原始的Bll层的实体类注册
        /// </summary>
        class OriginalBllModule : Autofac.Module
        {
            protected override void Load(ContainerBuilder builder)
            {
               
                base.Load(builder);
            }
        }
        #endregion
    }
}
Bootstrapper.cs

 

posted @ 2017-08-31 17:04  多加些蜂蜜  阅读(223)  评论(0编辑  收藏  举报