动态加载具有某些其他dll依赖项的.NET程序集 [英] Dynamic load a .NET assembly with some other dll dependency

查看:131
本文介绍了动态加载具有某些其他dll依赖项的.NET程序集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为我的应用程序创建一个插件引擎,但是我遇到一个问题:如何加载对其他程序集有依赖性的.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.dllC.dll等,然后运行. A.dll具有两种方法,例如A()B().而A()B()使用B.dllC.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程序集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆