none
Assembly.LoadFile load same assembly but different paths 导致不能调试被动态加载的assembly

    问题

  • 我们项目有个需求,某个程序每次运行时,都会把某个Assembly(ClassLibrary2.dll)拷贝一份到另一个目录,然后再用Assembly.LoadFile动态加载进来执行。

    如果当次LoadFile加载的ClassLibrary2.dll和上次LoadFile加载的ClassLibrary2.dll虽然路径不同,但version相同。那么这次LoadFile后,ClassLibrary2.dll对应的code就不能被调试了, 提示 no source code available. (这个问题是在vs2015才发现的,同样的代码,在vs2012是可以被调试的)

    我写了点简单代码来重现这个bug

    1- a class library

    namespace ClassLibrary2
    {
       public class Class1
       {
          public static void A()
          {
             Console.WriteLine(typeof(Class1).Assembly.Location);
          }
       }
    }

    2 - a console application to reproduce the bug

       class Program
       {
          static void Main(string[] args)
          {
             // copy\ClassLibrary2.dll and copy2\ClassLibrary2.dll is the same dll, just a copy
             string assemblypath = @"D:\Revit\Dev\Dev\Regression\API\ConsoleApplication1\ClassLibrary2\bin\Debug\copy\ClassLibrary2.dll";
             string assemblypath2 = @"D:\Revit\Dev\Dev\Regression\API\ConsoleApplication1\ClassLibrary2\bin\Debug\copy2\ClassLibrary2.dll";
    
             // load the copy\ClassLibrary2.dll
             Assembly assem = Assembly.LoadFile(assemblypath);
             // reload the same dll but different path - copy2\ClassLibrary2.dll 
             Assembly assem2 = Assembly.LoadFile(assemblypath2);
             // bug is here: there is a different in vs2012 and vs2015 when execute this sentence: 
             // in vs2012 output shows - ConsoleApplication1.vshost.exe' (CLR v4.0.30319: ConsoleApplication1.vshost.exe): Loaded 'D:\Revit\Dev\Dev\Regression\API\ConsoleApplication1\ClassLibrary2\bin\Debug\copys\ClassLibrary2.dll'. Symbols loaded.
             // in vs2015 output shows nothing. (So I think the assemblypath2 isn't loaded)
    
             Type type = assem2.GetType("ClassLibrary2.Class1");
             MethodInfo method = type.GetMethod("A");
             method.Invoke(null, null); // then invoke method "A" in assemblypath2 and step into this when debug
             // bug is here: there is a different in vs2012 and vs2015
             // in vs2012 - I can debug method A in ClassLibrary2.Class1. 
             // in vs2015 - cannot debug method A in ClassLibrary2.Class1, breakpoints are not hit. And Tthe Diagnostic tool shows "No Source Code Available"
          }
       }


    2016年1月8日 6:29

答案

全部回复