无法加载文件或程序集或其依赖项之一。该系统找不到指定的文件。 (不允许 GAC)

Could not load file or assembly or one of its dependencies. The system cannot find the file specified. (No GAC allowed)

我有 "Main" 程序,它使用反射动态加载我自己的 "plugin.dll" 文件。 "plugin.dll" 文件通过使用 visual studio 引用来引用第三方 "device.dll"。只要 "device.dll" 和 "plugin.dll" 与 "Main" 程序在同一个文件夹中,或者 "Main" 程序引用了 "plugin.dll" 一切正常。但是,一旦我将 "device.dll" 文件移动到另一个文件夹,我就会收到以下错误消息: "Could not load file or assembly or one of its dependencies. The system cannot find the file specified." 出现问题是因为程序没有找到"device.dll"文件。 "Copy Local" 属性 或 "Reference paths" 对这个问题没有任何影响。我知道我必须指定 "device.dll" 的路径,但如果不将 "plugin.dll" 和 "device.dll" 放入 GAC(全局程序集缓存),我找不到方法。 GAC 不是一个解决方案,因为第三方 dll 也必须是强名称的(再次反汇编和 assemble),这是版权许可所不允许的。

其他详细信息: 使用 visual studio 2013 和 .Net framework 4.0 FUSLOGVW 没有记录任何错误(知​​道为什么吗?)。

期待您的建议, 提前致谢。

检查 AppDomain.AssemblyResolve 事件。这是您可以执行自定义操作以在非默认位置加载程序集的理想点。

我在此处添加链接的 MSDN 文章的引用:

It is the responsibility of the ResolveEventHandler for this event to return the assembly that is specified by the ResolveEventArgs.Name property, or to return null if the assembly is not recognized. The assembly must be loaded into an execution context; if it is loaded into the reflection-only context, the load that caused this event to be raised fails.

归根结底,这意味着您的应用程序或服务将进入 AssemblyResolve 事件情况,即无法使用默认程序集发现方法加载程序集(AppDomain.BaseDirectory全局程序集缓存...)。

一旦引发所谓的事件,您需要 return Assembly 的一个实例,您的工作是决定 如何 加载程序集(来自文件、流、字节...)。也就是说,如果您将插件程序集放在某个子目录中或谁知道在哪里,您可以使用正确的完整程序集路径调用 Assembly.Load 来加载它们并避免程序集加载问题。