问题
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()
?
回答1:
Use AssemblyResolve event in the current AppDomain:
To load DLLs:
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}");
}
来源:https://stackoverflow.com/questions/26119874/dynamic-load-a-net-assembly-with-some-other-dll-dependency