ASP.NET MVC中使用Autofac依賴注入

 
 
ASP.NET MVC中使用Autofac依賴注入
2024年02月26日在.net 4.8 framework 建立的MVC項目中測試通過
引入NUGET包:Autofac和Autofac.Mvc5
Global中加入以下代碼:
 
 //autofac注入
 ContainerBuilder builder = new ContainerBuilder();
 // Register your MVC controllers. (MvcApplication is the name of
 // the class in Global.asax.)
 builder.RegisterControllers(typeof(MvcApplication).Assembly);
 builder.RegisterType<DAL.StudentRepository>().As<DAL.IStudent>();   //這是自己寫的接口及實現
 //移除原本的mvc的容器,使用AutoFac的容器,將MVC的控制器對象實例交由autofac來創建
 var container = builder.Build();
 DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
HomeController中的注入代碼:
 
        private readonly IStudent dal;

        public HomeController(IStudent dal)
        {
            this.dal = dal;
        }

 

 
 
然後就可以直接用接口裏定義的方法了
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章