0%

复制代码

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中配置

我web.config中引用一个文件,详细看我之前的博文

复制代码

复制代码

然后在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