using System; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; namespace Sinvo.EplanHpD.Plugin { public class AppDomainDllLoader { public static bool isLoaded = false; public static void SetLaoder() { if (isLoaded) { return; } // 接管DLL加载,解决依赖问题 // 插件被加载时,AppContext.BaseDirectory 会指向Eplan的安装目录,导致一部分依赖的DLL在加载时找不到 // 接管之后,从两个目录都查找一次 //throw new NotImplementedException(); try { // 防止重复加载 先卸载事件 AppDomain.CurrentDomain.AssemblyResolve -= AssemblyResolveHandle; } catch (Exception ex) { Trace.TraceError(ex.Message); } AppDomain.CurrentDomain.AssemblyResolve += AssemblyResolveHandle; isLoaded = true; } public static Assembly AssemblyResolveHandle(object sender, ResolveEventArgs args) { var assemblyName = new AssemblyName(args.Name); // 判断是否已经被加载 var loadedAssembly = AppDomain.CurrentDomain.GetAssemblies() .FirstOrDefault(a => a.FullName == assemblyName.FullName); if (loadedAssembly != null) { Debug.WriteLine($"DLL is loaded -> {loadedAssembly.FullName}"); return loadedAssembly; } // 从当前路径下加载 var path = Path.Combine(AppContext.BaseDirectory, $"{assemblyName.Name}.dll"); if (File.Exists(path)) { Debug.WriteLine($"Load dll for path -> {path}"); return Assembly.LoadFile(path); } var envPath = System.Environment.CurrentDirectory; // 从插件路径中加载依赖 path = Path.Combine(Path.GetDirectoryName(Assembly.GetAssembly(typeof(AppDomainDllLoader)).Location), $"{assemblyName.Name}.dll"); if (File.Exists(path)) { //MessageBox.Show($"Load dll for self path -> {path}"); Debug.WriteLine($"Load dll for self path -> {path}"); return Assembly.LoadFile(path); } //MessageBox.Show(path); Debug.WriteLine($"File not load! -> {path}"); return null; } } }