我有一个自定义 MSBuild 任务,它可以在程序集中查看一些属性元数据。
Assembly assembly = Assembly.ReflectionOnlyLoadFrom(AssemblyFile)
我们的自动化构建/发布过程使用了这一点,并且与类库、控制台应用程序和 Web 项目使用和引用的程序集完美匹配。在另一个 MSBuild 进程编译项目后调用 MSBuild 任务。
昨天当我添加一个引用这个特定程序集的 WPF 项目时它停止工作 - 一个 .NET 3.5 类库。
System.IO.FileLoadException: API restriction: The assembly 'file:///bogus.dll' has already loaded from a different location.
It cannot be loaded from a new location within the same appdomain.
at System.Reflection.Assembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection)
at System.Reflection.Assembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection)
at System.Reflection.Assembly.InternalLoad(AssemblyName assemblyRef, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection)
at System.Reflection.Assembly.InternalLoadFrom(String assemblyFile, Evidence securityEvidence, Byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm, Boolean forIntrospection, StackCrawlMark& stackMark)
at System.Reflection.Assembly.ReflectionOnlyLoadFrom(String assemblyFile)
at RadicaLogic.MSBuild.Tasks.GetAssemblyAttribute.Execute()
at Microsoft.Build.BuildEngine.TaskEngine.ExecuteInstantiatedTask(EngineProxy engineProxy, ItemBucket bucket, TaskExecutionMode howToExecuteTask, ITask task, Boolean& taskResult)
我知道它与 WPF 相关,因为如果我将 AssemblyFile 更改为指向 WPF 项目未引用的同一解决方案中的另一个程序集,则不会引发异常。
异常消息提到
... already loaded from a different location.
It cannot be loaded from a new location within the same appdomain.
请注意有关相同应用程序域的部分。
所以我修改了代码来捕捉这个特殊的异常并查看 CurrentDomain:
Assembly assembly = null;
try
{
assembly = Assembly.ReflectionOnlyLoadFrom(AssemblyFile);
}
catch (FileLoadException)
{
List<string> searched = new List<string>();
foreach (var asm in AppDomain.CurrentDomain.GetAssemblies())
{
if (Path.GetFileName(asm.CodeBase).Equals(Path.GetFileName(AssemblyFile),
StringComparison.OrdinalIgnoreCase))
{
message = string.Format("Found assembly {0} in current domain",
asm.CodeBase);
MSBuildHelper.Log(this, message, MessageImportance.High);
assembly = asm;
break;
}
else
{
searched.Add(Path.GetFileName(asm.CodeBase));
}
}
if (assembly == null)
{
message = string.Format(
"Unable to find {0} after looking in current domain assemblies {1}",
Path.GetFileName(AssemblyFile), string.Join(", ", searched.ToArray()));
MSBuildHelper.Log(this, message, MessageImportance.High);
}
}
不用说,有问题的程序集不在当前域中(这可能是有道理的,因为产生了另一个 MSBuild 进程来进行编译),所以假设错误消息是真的,我该如何弄清楚在哪里它活着?这很令人困惑,因为给我的错误消息表明它应该是 CurrentDomain。
或者有更多 WPF 经验的人可以解释为什么这个程序集在成功构建后仍然在应用程序域中浮动?
这是其他遇到此异常的人提出的另一个问题。