前段時間也研究了其餘IOC框架,如unity、Castle、Autofac,相對來講Autofac比較簡單,聽說也是效率最高的。首先了解下控制反轉和依賴注入 IoC把建立依賴對象的控制權交給了容器,由容器進行注入對象,因此對象與對象之間是鬆散耦合,利於功能複用,也使得程序的整個體系結構變得很是靈活。html
控制反轉Ioc:調用者不主動建立被調用者實例,由IoC容器來建立;架構
依賴注入DI:把依賴關係注入到調用者;框架
Autofac+Mvc4 項目架構ide
Student.cs實體函數
1 public class Student 2 { 3 public string name { get; set; } 4 public int age { get; set; } 5 public string gender { get; set; } 6 }
IStudentRepository.cs接口ui
1 public interface IStudentRepository 2 { 3 IEnumerable<Student> GetAll(); 4 }
StudentRepository實現接口this
1 public class StudentRepository : IStudentRepository 2 { 3 private List<Student> Articles = new List<Student>(){ 4 new Student { name = "張三", gender = "male", age = 12 }, 5 new Student { name = "李四", gender = "fmale", age = 15 }, 6 new Student { name = "王五", gender = "fmale", age = 13 }}; 7 8 /// <summary> 9 /// 獲取所有學生信息 10 /// </summary> 11 /// <returns></returns> 12 public IEnumerable<Student> GetAll() 13 { 14 return Articles; 15 } 16 }
HomeControll.cs控制器spa
1 #region [AutoFac注入] 2 3 readonly IStudentRepository repository; 4 //構造器注入 5 public HomeController(IStudentRepository repository) 6 { 7 this.repository = repository; 8 } 9 10 /// <summary> 11 /// AutoFac注入 12 /// </summary> 13 /// <returns></returns> 14 public ActionResult StudentIndex() 15 { 16 var data = repository.GetAll(); 17 return View(data); 18 } 19 #endregion
在App_Start文件夾中添加AutofacConfig.cs文件code
1 public class AutofacConfig 2 { 3 /// <summary> 4 /// 負責調用autofac框架實現業務邏輯層和數據倉儲層程序集中的類型對象的建立 5 /// 負責建立MVC控制器類的對象(調用控制器中的有參構造函數) 6 /// </summary> 7 public static void Register() 8 { 9 ContainerBuilder builder = new ContainerBuilder(); 10 SetupResolveRules(builder); 11 builder.RegisterControllers(Assembly.GetExecutingAssembly()); 12 builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).AsImplementedInterfaces(); 13 var container = builder.Build(); 14 DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); 15 16 } 17 /// <summary> 18 /// 全部須要注入的類型 19 /// </summary> 20 /// <param name="builder"></param> 21 private static void SetupResolveRules(ContainerBuilder builder) 22 { 23 builder.RegisterType<StudentRepository>().As<IStudentRepository>(); 24 } 25 }
在Global.asax.cs類Application_Start方法中註冊Autofac htm
1 public class MvcApplication : System.Web.HttpApplication 2 { 3 protected void Application_Start() 4 { 5 AreaRegistration.RegisterAllAreas(); 6 7 WebApiConfig.Register(GlobalConfiguration.Configuration); 8 FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 9 RouteConfig.RegisterRoutes(RouteTable.Routes); 10 BundleConfig.RegisterBundles(BundleTable.Bundles); 11 12 AutofacConfig.Register();//AutoFac注入 13 } 14 }
執行程序返回數據
能夠參考http://www.cnblogs.com/bubugao/p/AutofacDemo.html文章,簡單明瞭解釋Autofac做用。