使用 Assembly.loadfrom() 时如何解决程序集在 C# 中的依赖性

How to address an assembly's dependency in C# when using Assembly.loadfrom()

我创建了一个 C++ 包装器 class 库来导入 C++ 本机 dll。我已将此 C++ class 库的项目引用添加到我的 C# 应用程序,并将所有依赖项复制到 Debug 文件夹。到目前为止,一切都运行良好,除非我想对该 C++ 本机 dll 的旧版本执行相同的过程。显然,我不能有两个具有相同名称的 dll,并且文件夹中的依赖项也具有相同的名称。所以我决定为每个版本的 c++ 包装器都有一个 c# 程序集包装器,并将每个程序集 dll 及其依赖项放在一个单独的文件夹中。

鉴于我不能再使用项目引用,因为它需要将引用 dll 复制到可执行应用程序的同一文件夹中,我尝试使用 Assembly.LoadFrom() 在 运行 时间加载包装程序集并加载程序集,但是当它到达 Invkode 行时:

bject[] p = new object[] { command, null,format,handle};
uint ret= (uint) mi.Invoke(obj,p)

它抛出一个异常说:

Could not load file or assembly 'MDVRCLib, Version=1.0.6110.25310, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.

再说一次,如果我将此程序集用作项目引用并将其所有依赖项复制到项目文件夹,它将正常工作。我想知道当我使用 Assembly.LoadFrom() 从不同的文件夹加载程序集时,如何解决程序集的依赖关系,以防止出现此类错误?

您可以附加到 静态 AssemblyResolve 事件

AppDomain.CurrentDomain.AssemblyResolve += (s, e) =>
{
    //determine the required assembly using "e.Name"
    var filename = "....."; 
    return Assembly.LoadFile(filename)
};

除了 AssemblyResolve 事件,'probing' 元素还可以像这样在应用程序配置文件中使用:

<configuration>
   <runtime>
      <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
         <probing privatePath="bin;bin2\subbin;bin3"/>
      </assemblyBinding>
   </runtime>
</configuration>

privatePath 包含要在其中搜索程序集的文件夹(相对于可执行文件)。