Dynamic load a .NET assembly with some other dll dependency

风流意气都作罢 提交于 2019-12-11 00:44:41

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!