public static void BuildMvcContainer() { var builder = new ContainerBuilder(); var assemblys = AppDomain.CurrentDomain.GetAssemblies().ToList(); //拆分DLL後需要注冊,需要注入的DLL Assembly[] asm = GetAllAssembly("*.Controllers.dll").ToArray(); builder.RegisterAssemblyTypes(asm); //讀取web.config中配置的值 builder.RegisterModule(new ConfigurationSettingsReader("autofac")); var container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); }
#region 加載程序集 private static List<Assembly> GetAllAssembly(string dllName) { List<string> pluginpath = FindPlugin(dllName); var list = new List<Assembly>(); foreach (string filename in pluginpath) { try { string asmname = Path.GetFileNameWithoutExtension(filename); if (asmname != string.Empty) { Assembly asm = Assembly.LoadFrom(filename); list.Add(asm); } } catch (Exception ex) { Console.Write(ex.Message); } } return list; } //查找所有插件的路徑 private static List<string> FindPlugin(string dllName) { List<string> pluginpath = new List<string>(); string path = AppDomain.CurrentDomain.BaseDirectory; string dir = Path.Combine(path, "bin"); string[] dllList = Directory.GetFiles(dir, dllName); if (dllList.Length > 0) { pluginpath.AddRange(dllList.Select(item => Path.Combine(dir, item.Substring(dir.Length + 1)))); } return pluginpath; } #endregion
上面的代碼就是注冊的代碼,我是在MVC4使用,寫完之後再Global.asax中的Application_Start調用,確保啟動應用後執行
然後是web.config中配置
<autofac configSource="Configuration\autofac.config" />
我web.config中引用一個文件,詳細看我之前的博文
<?xml version="1.0" encoding="utf-8"?> <autofac> <components> <component type="Cactus.Service.TestServer, Cactus.Service" service="Cactus.IService.TestInterface,Cactus.IService" /> <component type="Cactus.Service.SiteConfigService, Cactus.Service" service="Cactus.IService.ISiteConfigService,Cactus.IService" /> <component type="Cactus.Service.ActionGroupServer, Cactus.Service" service="Cactus.IService.IActionGroupServer,Cactus.IService" /> <component type="Cactus.Service.ActionServer, Cactus.Service" service="Cactus.IService.IActionServer,Cactus.IService" /> <component type="Cactus.Service.RoleServer, Cactus.Service" service="Cactus.IService.IRoleServer,Cactus.IService" /> <component type="Cactus.Service.UserServer, Cactus.Service" service="Cactus.IService.IUserServer,Cactus.IService" /> </components> </autofac>
然後在autofac.config中注冊服務,type是實現的server,service是接口
在MVC中的使用,根據的是構造函數注入
public class AdminLoginController : Controller { public readonly IUserServer userServer; public AdminLoginController(IUserServer userServer) { this.userServer = userServer; } public ActionResult Index() { userServer.xxxxx//隨便寫 return View(); } }
屬性注入可以參考這篇文章http://www.cnblogs.com/peteryu007/p/3449315.html