using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.Loader; using System.Text; using System.Threading.Tasks; using 加载Dll; namespace 加载dll { class 加载插件上下文 : AssemblyLoadContext { private AssemblyDependencyResolver? _解析器; public 加载插件上下文(string 插件路径) { _解析器 = new AssemblyDependencyResolver(插件路径); } protected override Assembly? Load(AssemblyName 程序集名称) { string? 程序集路径 = _解析器?.ResolveAssemblyToPath(程序集名称); if (程序集路径 != null) { return LoadFromAssemblyPath(程序集路径);//从路径加载程序集 } return null; } protected override IntPtr LoadUnmanagedDll(string 非托管DLL名称)//重写加载非托管DLL方法 { string? libraryPath = _解析器?.ResolveUnmanagedDllToPath(非托管DLL名称);//解析非托管类型DLL为路径 if (libraryPath != null) { return LoadUnmanagedDllFromPath(libraryPath);//从路径加载程序集 } return IntPtr.Zero; } static Assembly LoadPlugin(string relativePath) { // Navigate up to the solution root string root = Path.GetFullPath(Path.Combine( Path.GetDirectoryName( Path.GetDirectoryName( Path.GetDirectoryName( Path.GetDirectoryName( Path.GetDirectoryName(typeof(Program).Assembly.Location))))))); string pluginLocation = Path.GetFullPath(Path.Combine(root, relativePath.Replace('\\', Path.DirectorySeparatorChar))); Console.WriteLine($"Loading commands from: {pluginLocation}"); 加载插件上下文 loadContext = new 加载插件上下文(pluginLocation); return loadContext.LoadFromAssemblyName(new AssemblyName(Path.GetFileNameWithoutExtension(pluginLocation))); } } }