2015/07/23 Edit: All of these problems should now be fixed in the latest Roslyn NuGet packages
We first looked at MSBuildWorkspace
in Part 6 Working with Workspaces. MSBuildWorkpace
works really well when loading up solutions from .sln
files. It properly understands .csproj
files so we don’t have to worry about tracking down references, documents, or MSBuild targets.
However, when compiling solutions that contained Portable Class Libraries (PCLs) I had been continuously running into frustrating problems with missing references to System.Runtime.dll
. For example I’d see a handful of errors like:
error CS0012: The type 'Object' is defined in an assembly that is not referenced.
You must add a reference to assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.
I’d also seen this issue pop up within Visual Studio when working on XAML and when debugging.
After learning some more about PCLs, it turns out that PCLs must reference facade assemblies that delegate the actual work to proper assemblies later. For the full story on PCLs and facade references see: http://alxandr.me/2014/07/20/the-problems-with-portable-class-libraries-and-the-road-to-solving-them/
In our case we needed to add a reference to System.Runtime.dll
. I won’t bother to show the code for this as it’s fraught with its own set of problems. Although it resolves our System.Object
reference, we quickly run into other problems with other types such as System.Tasks.Task
. Manually adding these references was definitely not going to scale.
The Workaround
Originally this problem was reported as a bug within MSBuildWorkspace
. After all, why wouldn’t it resolve the references properly when we open the solution? Visual Studio obviously seemed to be capable of figuring the references out…
It turns out there’s a MSBuild property called CheckForSystemRuntimeDependency
. And we can set this to true and all our PCL worries seem to go away.
Simply create your MSBuildWorkspace with:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var ws = MSBuildWorkspace.Create(new Dictionary<string, string> { { "CheckForSystemRuntimeDependency", "true" } }); |
That’s it. That’s all. And best of all the Roslyn team will be removing this property when Roslyn v1.0 ships.
More info may be found at: https://github.com/dotnet/roslyn/issues/560
Thanks to @Pilchie and @JasonMalinowski for helping out with this problem and for the workaround!