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

时间:2018-06-01 19:15:52

标签: c# debugging visual-studio-2017 roslyn

我正在使用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选项?

1 个答案:

答案 0 :(得分:9)

下面的代码示例应为您提供帮助。它基于threre 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;
    }
}

用法:

[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");
}