A lightweight utility library to create a Roslyn
AdhocWorkspace from an existing
csproj, by capturing the CSharp compiler emited command while rebuilding the project. This can be used primarily for syntax tree inspection/code generation.
This library requires a
dotnetSDK to be installed
// Rebuild the specified project in Release and capture var result = CSharpCompilationCapture.Build(@"C:\Path\To\A\Sln\Or\project.csproj", "Release"); var workspace = result.Workspace; var project = workspace.CurrentSolution.Projects.FirstOrDefault(); var compilation = await project.GetCompilationAsync(); // ...
If you have been using
MSBuildWorkdspace to get an access to CSharp projects, you will find sometimes that it is actually impossible to work with if you are expecting your Roslyn application to run on a different runtime than the one currently installed through the
This is a known issue Use more permissive load context for MSBuildWorkspace by default and I hope that it will be fix in the future.
To workaround this problem and allow to load a CSharp Project with Roslyn no matter which SDK is installed, Broslyn is working like this:
- It runs a
dotnet msbuild /t:rebuildon the project or solution passed to it with an output to a binlog file.
- By running the re-build, we are able to capture the exact
csccommand issued by the build system and we can extract them with by reading compiler invocations using the fantastic MSBuildStruturedLog library.
- We then extract the csc arguments and transform them back to
- From this we can create for each
cscinvocation and equivalent Roslyn
Projectthat will guarantee the exact same compilation settings.
This was a nice suggestion from Kirill Osenkov (the author of MSBuildStruturedLog) and it turns out that it was very easy to implement.
This software is released under the BSD-Clause 2 license.
- Buildalizer: A more featured library if you are looking for a better introspection on project references and dependencies
- In Broslyn, a Project will only contain assembly references in order to compile to CSharp but will not provide full introspection on the original project references.
Alexandre Mutel aka xoofx.