示例#1
0
        public static void Excute(Action <ContainerBuilder> IocRegisterFun)
        {
            var builder   = new ContainerBuilder();
            var baseType  = typeof(IDependency);
            var assemblys = AppDomain.CurrentDomain.GetAssemblies().ToList().Where(t => { return(t.FullName.Contains("Controllers") | t.FullName.Contains("Filters") | t.FullName.Contains("Models") | t.FullName.Contains("BLL") | t.FullName.Contains("DAL") | t.FullName.Contains("Tmp") | t.FullName.Contains("App_Code")); });

            builder.RegisterControllers(assemblys.ToArray());
            builder.RegisterFilterProvider();
            builder.RegisterGeneric(typeof(EfRepository <>)).As(typeof(IRepository <>)).InstancePerLifetimeScope();
            builder.RegisterAssemblyTypes(assemblys.ToArray()).Where(t => baseType.IsAssignableFrom(t) & t != baseType).AsImplementedInterfaces().InstancePerLifetimeScope();
            IocRegisterFun(builder);

            //注入Cache
            //builder.RegisterGeneric(typeof(HttpContextCacheManager)).As(typeof(IHttpContextCacheManager)).InstancePerLifetimeScope();
            //builder.RegisterGeneric(typeof(HttpContextSessionManager)).As(typeof(IHttpContextSessionManager)).InstancePerLifetimeScope();
            //builder.RegisterGeneric(typeof(HttpContextSessionManager)).As(typeof(IHttpContextCacheManager)).InstancePerLifetimeScope();


            //设置相关全局变量
            IocContainerManager.SetInstance(builder.Build());
            IocObjectManager.SetInstance(new IocObjectManager(new IocLifetimeScope()));
            DependencyResolver.SetResolver(new AutofacDependencyResolver(IocContainerManager.GetInstance()));

            //RazorViewEngine设置
            ViewEngines.Engines.Clear();
            ViewEngines.Engines.Add(new TmpRazorViewEngine());

            AutoMapperConfig();
            RouteConfig();
        }
        public T Resolve <T>() where T : IDependency
        {
            var timeScope = AutofacDependencyResolver.Current.RequestLifetimeScope;

            if (timeScope == null)
            {
                var            container = IocContainerManager.GetInstance();
                ILifetimeScope scope;

                if (HttpContext.Current != null && (scope = (ILifetimeScope)HttpContext.Current.Items["PerRequestScope"]) != null)
                {
                    return(scope.Resolve <T>());
                }
                else
                {
                    var scope1 = container.BeginLifetimeScope();
                    HttpContext.Current.Items["PerRequestScope"] = scope1;
                    return(scope1.Resolve <T>());
                }
            }
            else
            {
                return(timeScope.Resolve <T>());
            }
        }