AssemblyResolve巧解未能載入檔案或程式集“Newtonsoft.Json, Version=6.0.0.0的問題

JohnYang819發表於2024-04-27

問題:未能載入檔案或程式集“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。
問題解決。

相關文章