zoukankan      html  css  js  c++  java
  • autofac

                var builder = new ContainerBuilder();
                builder.RegisterModule<AttributedMetadataModule>();
    
                builder.RegisterModule(new ConfigurationSettingsReader());  
      
                //如果是多个dll含有,要调用多次
                builder.RegisterControllers(typeof(MvcApplication).Assembly)
                        .PropertiesAutowired()  //注入到属性
                        .InstancePerHttpRequest();
                
                builder.RegisterSource(new ViewRegistrationSource());
    
               
                var container = builder.Build();
    
                DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
              

    在Global.asax.cs的Application_Start加入这段,我是习惯单独一个类里的一个方法做这个,然后被Application_Start调用

        public class LeaveController : Controller
        {
            private readonly IComponentContext _icoContext;
            private Lazy<ITest> Test
            {
                get;
                set;
            }
    
            public LeaveController(Lazy<ITest> test,IComponentContext icoContext)
            {
                _icoContext = icoContext;
                this.Test = test;
            }
            /// <summary>
            /// 用IComponentContext 来获得,显式调用Resolve
            /// </summary>
            /// <returns></returns>
            public ActionResult ContextIndex()
            {
                
                var test2 = _icoContext.Resolve<ITest>();
    
                return View("Index", "", test2.Test());
            }
    
            /// <summary>
            /// 用ApplicationContainer 来获得,显式调用Resolve
            /// </summary>
            /// <returns></returns>
            public ActionResult ApplicationIndex()
            {
                var test3 = AutofacDependencyResolver.Current.ApplicationContainer.Resolve<ITest>();
    
                return View("Index", "", test3.Test());
            }
            /// <summary>
            /// 用构造函数的Lazy加载
            /// </summary>
            /// <returns></returns>
            public ActionResult Index()
            {
                return View("Index", "", this.Test.Value.Test());
            }
    
        }

    用构造函数注入的比较常见,IComponentContext和

     AutofacDependencyResolver.Current.ApplicationContainer另外做法
  • 相关阅读:
    c语言中编写标准身高体重对照表
    c语言实现约数的枚举
    c语言中循环输出1234567890
    c语言中为九九乘法增加横纵标题
    c语言中多重循环
    c语言中绘制金字塔
    c语言中双重循环
    c语言中绘制长方形
    当当网代码1
    当当网代码4
  • 原文地址:https://www.cnblogs.com/peteryu007/p/3449315.html
Copyright © 2011-2022 走看看