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另外做法
  • 相关阅读:
    VS2005在使用membership的时候,如何连接Access数据库?
    今天想开始写计划的项目,可是就是静不下心来,乱糟糟的!
    今天想开始写计划的项目,可是就是静不下心来,乱糟糟的!
    有钱真好
    网页左边和上面的空隙如何设置成为0
    vim 配色方案(目测有上百个)
    Git 远程仓库的管理和使用
    vim 使用图
    Python 编程挑战
    python 网络爬虫
  • 原文地址:https://www.cnblogs.com/peteryu007/p/3449315.html
Copyright © 2011-2022 走看看