如何调试从Roslyn编译生成的DLL?

dnf*_*dnf 6 c# debugging roslyn visual-studio-2017

我正在使用Roslyn CSharpCompilation为我的插件生成dll文件 - 文件包含OptimizationLevel.Debug并生成pdb文件.接下来我使用Assembly.Load将这些文件加载​​到我的程序(UWP + .NET Standard 2.0库)并创建我感兴趣的类型的实例.我的问题是我无法获得Visual Studio(版本2017 15.7. 3)在我调试时找到源代码 - 它正在像外部库一样踩踏它,所以当异常被抛入里面时我无法找到它.我已经厌倦了在stackoverflow上搜索解决方案,但所有解决方案都无法正常工作.我检查过这个:

  • 生成Pdb
  • VS中的模块窗口显示已加载符号
  • 尝试了不同版本的Assembly Load/LoadFrom
  • 在调试选项中设置"使用托管兼容模式"

有没有办法让文件可调试?也许在编译或改变VS中的某些东西时我必须使用一些roslyn选项?

小智 11

下面的代码示例应该可以帮助您.它基于Thlamare IOC容器的代码生成部分,它是Jeremy D Miller制作的StructureMap的继承者.

我只添加了调试功能.诀窍是使源文本可嵌入,选择正确的格式,并在需要时设置编码值.

查看原始工作以获取更多详细信息,例如添加参考.

public Assembly CreateAssembly(string code)
{
    var encoding = Encoding.UTF8;

    var assemblyName = Path.GetRandomFileName();
    var symbolsName = Path.ChangeExtension(assemblyName, "pdb");
    var sourceCodePath = "generated.cs";

    var buffer = encoding.GetBytes(code);
    var sourceText = SourceText.From(buffer, buffer.Length, encoding, canBeEmbedded: true);

    var syntaxTree = CSharpSyntaxTree.ParseText(
        sourceText, 
        new CSharpParseOptions(), 
        path: sourceCodePath);

    var syntaxRootNode = syntaxTree.GetRoot() as CSharpSyntaxNode;
    var encoded = CSharpSyntaxTree.Create(syntaxRootNode, null, sourceCodePath, encoding);

    var optimizationLevel = OptimizationLevel.Debug;

    CSharpCompilation compilation = CSharpCompilation.Create(
        assemblyName,
        syntaxTrees: new[] { encoded },
        references: references,
        options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
            .WithOptimizationLevel(optimizationLevel)
            .WithPlatform(Platform.AnyCpu)
    );

    using (var assemblyStream = new MemoryStream())
    using (var symbolsStream = new MemoryStream())
    {
        var emitOptions = new EmitOptions(
                debugInformationFormat: DebugInformationFormat.PortablePdb,
                pdbFilePath: symbolsName);

        var embeddedTexts = new List<EmbeddedText>
        {
            EmbeddedText.FromSource(sourceCodePath, sourceText),
        };

        EmitResult result = compilation.Emit(
            peStream: assemblyStream,
            pdbStream: symbolsStream,
            embeddedTexts: embeddedTexts,
            options: emitOptions);

        if (!result.Success)
        {
            var errors = new List<string>();

            IEnumerable<Diagnostic> failures = result.Diagnostics.Where(diagnostic =>
                diagnostic.IsWarningAsError ||
                diagnostic.Severity == DiagnosticSeverity.Error);

            foreach (Diagnostic diagnostic in failures)
                errors.Add($"{diagnostic.Id}: {diagnostic.GetMessage()}");

            throw new Exception(String.Join("\n", errors));
        }

        Console.WriteLine(code);

        assemblyStream.Seek(0, SeekOrigin.Begin);
        symbolsStream?.Seek(0, SeekOrigin.Begin);

        var assembly = AssemblyLoadContext.Default.LoadFromStream(assemblyStream, symbolsStream);
        return assembly;
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

[Test]
public void Verify()
{
    var code =
        @"namespace Debuggable
        {
            public class HelloWorld
            {
                public string Greet(string name)
                {
                    var result = ""Hello, "" + name;
                    return result;
                }
            }
        }
        ";

    var codeGenerator = new CodeGenerator();
    var assembly = codeGenerator.CreateAssembly(code);

    dynamic instance = assembly.CreateInstance("Debuggable.HelloWorld");

    // Set breakpoint here
    string result = instance.Greet("Roslyn");

    result.Should().Be("Hello, Roslyn");
}
Run Code Online (Sandbox Code Playgroud)