项目使用的MVC4,.net 4.5 Nuget安装最新的autofac,一直提示不支持.net 4.5。没办法了,最后用Nuget控制台安装的老版本。因为我使用的是MVC4,所以直接安装的是autofac mvc4的集成。
命令:
Install-Package Autofac.Mvc4
安装成功。
示例如下:
var builder = new ContainerBuilder(); builder.RegisterControllers(typeof(MvcApplication).Assembly); builder.RegisterType<Cms.BLL.SysManagementService>().As<ISysManagementService>(); var container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
第一行声明IoC的builder
第二行绑定程序集中的Controllers
第三行注入我们需要的接口对应的实现
第四行获取IoC的容器
第五行,利用MVC的依赖解析接口,将autofac的依赖解析传入
需要特别注意第二行:要注册的Controllrs所在的程序集。也就说,如果Controllers是一个独立的项目,那么需要传递相应的程序集名称。示例如下:
var builder = new ContainerBuilder(); Assembly[] asm = GetAllAssembly("*.Controllers.dll").ToArray(); builder.RegisterControllers(asm); builder.RegisterType<Cms.BLL.SysManagementService>().As<ISysManagementService>(); var container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
/// <summary> /// 获取dll中Controller程序集 /// </summary> /// <param name="dllName"></param> /// <returns></returns> 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; } /// <summary> /// 查找dll路径 /// </summary> /// <param name="dllName"></param> /// <returns></returns> 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; }
参考:http://www.lxway.com/45068094.htm
(这个点上坑了半天,一直报错“没有为该对象定义无参数的构造函数”,以为是autofac没入门,自己代码写错了。其实是自己分切了Controllers为独立项目,结果还一直在绑定Mvc的程序集,所以根本找不到注入)