如何在当前Visual Studio主机内的Visual Studio扩展中调试使用Roslyn编译的代码
本文关键字:Visual Studio 调试 代码 编译 Roslyn 主机 扩展 | 更新日期: 2023-09-27 18:29:09
我有一个Visual Studio扩展,它使用Roslyn在当前打开的解决方案中获取项目,编译它并从中运行方法。程序员可以修改该项目。
我已经在当前VisualStudioWorkspace的Visual Studio扩展中成功编译了一个项目。
private static Assembly CompileAndLoad(Compilation compilation)
{
using (MemoryStream dllStream = new MemoryStream())
using (MemoryStream pdbStream = new MemoryStream())
{
EmitResult result = compilation.Emit(dllStream, pdbStream);
if (!result.Success)
{
IEnumerable<Diagnostic> failures = result.Diagnostics.Where(diagnostic =>
diagnostic.IsWarningAsError ||
diagnostic.Severity == DiagnosticSeverity.Error);
string failuresException = "Failed to compile code generation project : 'r'n";
foreach (Diagnostic diagnostic in failures)
{
failuresException += $"{diagnostic.Id} : {diagnostic.GetMessage()}'r'n";
}
throw new Exception(failuresException);
}
else
{
dllStream.Seek(0, SeekOrigin.Begin);
return AppDomain.CurrentDomain.Load(dllStream.ToArray(), pdbStream.ToArray());
}
}
}
然后我可以在当前域中加载程序集,获取它的类型并调用方法。
问题是,如果加载的解决方案的当前配置是调试的,我需要允许程序员设置断点。
我需要从扩展在当前的Visual Studio主机中运行一些代码,并允许在当前的VisualStudio实例中对其进行调试。
看起来这实际上是不可能的。
当前visual studio实例无法自行调试。
我尝试过用roslyn创建一个控制台应用程序,将其附加到调试器,然后从中运行生成代码。但VisualStudioWorkspace仅在VisualStudio中可用(不可序列化,也不可通过DTE-com接口使用)。因此,剩下的唯一解决方案就是使用MBBuildWorkspace。由于它与Visual studio工作区没有相同的行为,我放弃了这个项目。
以下是我的代码以供进一步参考:
Process vsProcess = Process.GetCurrentProcess();
string solutionPath = CurrentWorkspace.CurrentSolution.FilePath;
SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText($@"
using System;
using System.Threading.Tasks;
namespace CodeGenApplication
{{
public class Program
{{
public static void Main(string[] args)
{{
Console.ReadLine();
int vsProcessId = Int32.Parse(args[0]);
CodeGenApp.Test(""{solutionPath.Replace(@"'", @"''")}"", ""{projectName}"", ""{_codeGenProjectName}"");
Console.ReadLine();
}}
}}
}}");
string assemblyName = Path.GetRandomFileName();
Project codeGenProject = CurrentWorkspace.CurrentSolution.Projects.Where(x => x.Name == _codeGenProjectName).FirstOrDefault();
List<MetadataReference> references = codeGenProject.MetadataReferences.ToList();
CSharpCompilation compilation = CSharpCompilation.Create(
assemblyName,
syntaxTrees: new[] { syntaxTree },
references: references,
options: new CSharpCompilationOptions(OutputKind.ConsoleApplication));
// Emit assembly to streams.
EmitResult result = compilation.Emit("CodeGenApplication.exe", "CodeGenApplication.pdb");
if (!result.Success)
{
IEnumerable<Diagnostic> failures = result.Diagnostics.Where(diagnostic =>
diagnostic.IsWarningAsError ||
diagnostic.Severity == DiagnosticSeverity.Error);
}
else
{
Process codeGenProcess = new Process();
codeGenProcess.StartInfo.FileName = "CodeGenApplication.exe";
codeGenProcess.StartInfo.Arguments = vsProcess.Id.ToString();
codeGenProcess.StartInfo.UseShellExecute = false;
codeGenProcess.StartInfo.CreateNoWindow = true;
codeGenProcess.StartInfo.LoadUserProfile = true;
codeGenProcess.StartInfo.RedirectStandardError = true;
codeGenProcess.StartInfo.RedirectStandardInput = true;
codeGenProcess.StartInfo.RedirectStandardOutput = false;
codeGenProcess.Start();
foreach (EnvDTE.Process dteProcess in _dte.Debugger.LocalProcesses)
{
if (dteProcess.ProcessID == codeGenProcess.Id)
{
dteProcess.Attach();
}
}
codeGenProcess.StandardInput.WriteLine("Start");
}
您必须将调试器附加到当前运行的visualstudio主机。要做到这一点,您需要:
- 获取DTE对象
- 在DTE.Debugger.LocalProcesses中查找(当前)进程
- 附加调试器-示例
- 从已编译的程序集中运行方法
您可能需要一个单独的命令/按钮,而不仅仅是打开当前的构建配置。其他人都是这样做的(例如测试运行者,甚至Visual Studio)。此外,将编译后的Assembly
加载到一个新的AppDomain
中,否则它将永远存在。
还有一种更"创造性"的解决方案,即向即将运行的方法注入System.Diagnostics.Debugger.Launch()
调用(在调用Emit
之前修改正确的Compilation.SyntaxTrees
),但说真的,不要这样做。