c# - 如何调试 Roslyn 编译生成的 dll?

标签 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 选项?

最佳答案

下面的代码示例应该对您有所帮助。它基于 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;
    }
}

用法:

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

关于c# - 如何调试 Roslyn 编译生成的 dll?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50649795/

相关文章:

c# - 无法在 Visual Studio 2017 RC 中启动 IIS Express

c - 如何在不打印 (“pause” 的情况下执行系统 ​​ "Press enter to continue..."?

c# - 为什么我在编码网站上看到的大多数 DataContract 的 DataMembers 不是使用自动属性编写的?

debugging - 并行调试器

c# - 是否可以在不初始化 NHibernate 集合的情况下添加多对多关系?

c# - Visual Studio - 在不启动浏览器的情况下调试 Web 应用程序(运行本地 IIS)

C# 调用 C++ DLL 返回不正确的值

unit-testing - VS 2017未在.NET Core上发现测试

c# - "Global element ' 在web config中配置' has already been declared"

c# - Asp.Net MVC 有很多常量来处理 Controller /操作重定向