private static void SetAutofacWebAPI() { var builder = new ContainerBuilder(); #region 配置注冊方法 string dataType = ConfigurationManager.AppSettings["dataBaseType"].ToString().ToLower(); //var data = Assembly.Load("Model");//加載特定程序集 var data2 = Assembly.Load("MvcAdmin.Service");//加載特定程序集 switch (dataType) { case "mssql": builder.RegisterAssemblyTypes(data2) .Where(a => a.FullName.Contains("MvcAdmin.Service.MSSQLServer")).AsImplementedInterfaces(); break; case "mysql": builder.RegisterAssemblyTypes(data2) .Where(a => a.FullName.Contains("MvcAdmin.Service.MySQLServer")).AsImplementedInterfaces(); break; default: //builder.RegisterAssemblyTypes(data) // .Where(a => a.FullName.Contains("Model.MYSQL")).AsImplementedInterfaces(); builder.RegisterAssemblyTypes(data2) .Where(a => a.FullName.Contains("MvcAdmin.Service.MySQLServer")).AsImplementedInterfaces(); break; } #endregion builder.RegisterControllers(Assembly.GetExecutingAssembly()); var container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); }
看得出,去就是在web.config中加了一個數據庫的選擇,不加的話也會有默認的。之前有人說我用web.config配置太復雜了,所有出這篇。
復雜的這篇http://www.cnblogs.com/RainbowInTheSky/p/4531786.html
上面的代碼我在之前開源的小後台中有使用,地址:http://code.taobao.org/p/MvcAdmin/src/可以去看看裡面的啟動項代碼
另外在附上Autofac入門:
http://www.cnblogs.com/liping13599168/archive/2011/07/16/2108209.html(控制台演練)
http://www.cnblogs.com/jiagoushi/p/4084145.html(屬性注入)
http://www.cnblogs.com/n-pei/archive/2013/01/24/2875674.html(mvc演練)