AssemblyResolve巧解未能加载文件或程序集“Newtonsoft.Json, Version=6.0.0.0的问题

问题:未能加载文件或程序集“Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed”或它的某一个...
问题分析:
原因是因为引用的Microsoft.AspNet.SignalR.Client库的依赖项是6.0版本的Newtonsoft.Json,而且是动态加载进去的(用Assembly.LoadFrom),而主程序有v13的Newtonsoft.Json,
但降低版本后,将会导致其他模块出错,所以SignalR.Client的库在加载依赖项的时候,找不到v6版本的Newtonsoft.Json,就会报错。
解决办法:
在动态加载处添加以下代码:

AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;

private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
    string simpName = new AssemblyName(args.Name).Name;
    string path = AppDomain.CurrentDomain.BaseDirectory + simpName + ".dll";
    return Assembly.LoadFrom(path);

}

这段代码将会在找不到dll的时候调用,这时候强行给Newtonsoft.json的程序集指定为主程序的那个Newtonsoft.Json。
问题解决。

posted @ 2024-04-27 10:06  JohnYang819  阅读(14)  评论(0编辑  收藏  举报