动态加载具有其他一些 dll 依赖项的 .NET 程序集 [英] Dynamic load a .NET assembly with some other dll dependency
问题描述
我想为我的应用程序创建一个插件引擎,但我遇到了一个问题:如何加载对其他程序集有一定依赖性的 .Net 程序集(实际上是我的插件).
例如我要加载A.DLL
和A.DLL
需要B.dll
或C.dll
等运行.A.dll
有两个方法,例如A()
和B()
.而A()
或B()
使用了B.dll
或C.dll
的一些方法.>
如何动态加载A.DLL
并调用A()
或B()
?
在当前 AppDomain 中使用 AssemblyResolve 事件:
加载 DLL:
string[] dlls = { @"path1a.dll", @"path2.dll" };foreach(dll 中的字符串 dll){使用 (FileStream dllFileStream = new FileStream(dll, FileMode.Open, FileAccess.Read)){BinaryReader asmReader = new BinaryReader(dllFileStream);byte[] asmBytes = asmReader.ReadBytes((int)dllFileStream.Length);AppDomain.CurrentDomain.Load(asmBytes);}}//附加一个事件处理程序来管理程序集加载AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
事件处理程序检查程序集的名称并返回正确的名称:
private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args){AppDomain 域 = (AppDomain)sender;foreach(在domain.GetAssemblies() 中组装asm){如果(asm.FullName == args.Name){返回汇编;}}throw new ApplicationException($"找不到程序集{args.Name}");}
I want to create a plugin engine for my app, but I have a problem: How can I load a .Net assembly (Actually my plugin) which has some dependency to other assembly.
For example I want to load A.DLL
and A.DLL
need to B.dll
or C.dll
and so on to run. The A.dll
has two method such as A()
and B()
. And A()
or B()
use some method of B.dll
or C.dll
.
What should I do to dynamically load A.DLL
and call A()
or B()
?
Use AssemblyResolve event in the current AppDomain:
To load DLLs:
string[] dlls = { @"path1a.dll", @"path2.dll" };
foreach (string dll in dlls)
{
using (FileStream dllFileStream = new FileStream(dll, FileMode.Open, FileAccess.Read))
{
BinaryReader asmReader = new BinaryReader(dllFileStream);
byte[] asmBytes = asmReader.ReadBytes((int)dllFileStream.Length);
AppDomain.CurrentDomain.Load(asmBytes);
}
}
// attach an event handler to manage the assembly loading
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
The event handler checks for the name of the assembly and returns the right one:
private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
AppDomain domain = (AppDomain)sender;
foreach (Assembly asm in domain.GetAssemblies())
{
if (asm.FullName == args.Name)
{
return asm;
}
}
throw new ApplicationException($"Can't find assembly {args.Name}");
}
这篇关于动态加载具有其他一些 dll 依赖项的 .NET 程序集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!