问题描述
我想为我的应用程序创建一个插件引擎,但是我遇到一个问题:如何加载对其他程序集有依赖性的.Net程序集(实际上是我的插件).
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.
例如,我要加载A.DLL
,而A.DLL
需要加载B.dll
或C.dll
等,然后运行. A.dll
具有两种方法,例如A()
和B()
.而A()
或B()
使用B.dll
或C.dll
的某种方法.
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
.
如何动态加载A.DLL
并调用A()
或B()
?
What should I do to dynamically load A.DLL
and call A()
or B()
?
推荐答案
在当前AppDomain中使用AssemblyResolve事件:
Use AssemblyResolve event in the current AppDomain:
要加载DLL:
string[] dlls = { @"path1\a.dll", @"path2\b.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程序集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!