LoadDll/加载dll/加载插件上下文.cs

62 lines
2.2 KiB
C#
Raw Normal View History

2023-02-28 12:23:33 +08:00
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)));
}
}
}