无法在 appDomain 中加载程序集

Posted

技术标签:

【中文标题】无法在 appDomain 中加载程序集【英文标题】:Unable to load assembly in appDomain 【发布时间】:2013-06-10 09:05:41 【问题描述】:

直到最近我才通过调用 Assembly.LoadFrom 来加载我的程序集,一切正常。但是现在我需要将它加载到一个临时的 appDomain 中,但是在尝试将程序集加载到临时域中时,我一直遇到 FileLoadException。我试图将 appDomainSetup 参数传递给 CreateDomain 方法,但没有成功。

这是我的代码。

var tempDomain = AppDomain.CreateDomain("TempDomain");
Assembly sampleAssembly = tempDomain.Load(pathToDll);

我的程序集在我的应用程序基目录的子目录中

【问题讨论】:

【参考方案1】:

AppDomain.Load 将程序集加载到当前执行的 AppDomain 中,而不是“TempDomain”中。正如 MSDN 文档中所述:

此方法仅用于将程序集加载到当前 应用领域。提供此方法是为了方便 无法调用静态 Assembly.Load 的互操作性调用者 方法。要将程序集加载到其他应用程序域,请使用 CreateInstanceAndUnwrap 等方法。

现在,在您的情况下,调用失败是因为当前正在执行的 AppDomain(很可能是您的主 AppDomain)无法从子目录中找到程序集。当您尝试在加载上下文中加载程序集时,应确保这些程序集位于以下位置之一:

    AppDomain 的基本目录 在 AppDomain 的私有 bin 路径中指定的基本目录的子目录 GAC

有关更多信息,您可以查看以下文章:

How the Runtime Locates Assemblies

Best Practices for Assembly Loading

Back to Basics: Using Fusion Log Viewer to Debug Obscure Loader Errors

【讨论】:

以上是关于无法在 appDomain 中加载程序集的主要内容,如果未能解决你的问题,请参考以下文章

ApplicationManager.CreateObject 无法在新的 AppDomain 中加载程序集

在 AppDomain 问题中加载具有依赖项的程序集

在沙盒 Appdomain 中加载程序集 - SecurityException

在不同的 AppDomain 中加载具有依赖项的程序集

在新的 Appdomain 中加载程序集,需要完全信任父程序集

.NET 进程和 AppDomain 在啥情况下会共享内存中加载的程序集?