我如何编译罗斯林一个C#的解决方案?
我有一个软件,其基于用户行为C#项目生成代码。我想创建GUI来自动编译解决方案,所以我没有加载了Visual Studio的只是触发重新编译。
I have a piece of software that generates code for a C# project based on user actions. I would like to create a GUI to automatically compile the solution so I don't have to load up Visual Studio just to trigger a recompile.
我一直在寻找与罗斯林玩了一下,并有机会决定尝试使用罗斯林代替的MSBuild的做到这一点。不幸的是,我似乎无法找到这种方式使用罗斯林任何好的资源。
I've been looking for a chance to play with Roslyn a bit and decided to try and use Roslyn instead of msbuild to do this. Unfortunately, I can't seem to find any good resources on using Roslyn in this fashion.
任何人都可以点我在正确的方向?
Can anyone point me in the right direction?
您可以使用 Roslyn.Services.Workspace.LoadSolution
加载该解决方案。一旦你这样做,你需要经过每一个依赖顺序的项目,得到了编辑
项目和呼叫的Emit
就可以了。
You can load the solution by using Roslyn.Services.Workspace.LoadSolution
. Once you have done so, you need to go through each of the projects in dependency order, get the Compilation
for the project and call Emit
on it.
您可以得到相关性顺序编译的代码如下图所示。 (是的,我知道,不必强制转换为IHaveWorkspaceServices很烂,它会在未来的公开发行会更好,我保证)。
You can get the compilations in dependency order with code like below. (Yes, I know that having to cast to IHaveWorkspaceServices sucks. It'll be better in the next public release, I promise).
using Roslyn.Services;
using Roslyn.Services.Host;
using System;
using System.Collections.Generic;
using System.IO;
class Program
{
static void Main(string[] args)
{
var solution = Solution.Create(SolutionId.CreateNewId()).AddCSharpProject("Foo", "Foo").Solution;
var workspaceServices = (IHaveWorkspaceServices)solution;
var projectDependencyService = workspaceServices.WorkspaceServices.GetService<IProjectDependencyService>();
var assemblies = new List<Stream>();
foreach (var projectId in projectDependencyService.GetDependencyGraph(solution).GetTopologicallySortedProjects())
{
using (var stream = new MemoryStream())
{
solution.GetProject(projectId).GetCompilation().Emit(stream);
assemblies.Add(stream);
}
}
}
}
注1 : LoadSolution
仍然没有井盖解析的.csproj文件,并确定文件/引用/编译器选项下的MSBuild使用
Note1: LoadSolution
still does use msbuild under the covers to parse the .csproj files and determine the files/references/compiler options.
注2:由于罗斯林尚未语言完成,有可能会当您尝试这并不成功编译项目
Note2: As Roslyn is not yet language complete, there will likely be projects that don't compile successfully when you attempt this.