问题
I need to build a Xamarin solution (the UWP project of the solution) from a console application (another solution). In windows or web applications all the referenced files are listed in the project`s file. Therefore, I am able to simply emit the project's compilation and get the assembly file.
var solutionPath = "folder\solution name.sln";
var workspace = MSBuildWorkspace.Create();
var solution = await workspace.OpenSolutionAsync(solutionPath, CancellationToken);
var project = solution.Projects.First(x => x.Name.Contains("UWP", caseSensitive: false));
var compilation = await project.GetCompilationAsync();
var emitResult = compilation.Emit(stream);
But the Xamarin project's file says "A reference to the entire .Net Framework and Windows SDK are automatically included" so the emit method fails to build the project. I know that I could use create method of CSharpCompilation and pass the required metadata references to it but I do not know how I can pass entire .Net Framework and Windows SDK to it.
var solutionPath = "folder\solution name.sln";
var workspace = MSBuildWorkspace.Create();
var solution = await workspace.OpenSolutionAsync(solutionPath, CancellationToken);
var project = solution.Projects.First(x => x.Name.Contains("UWP", caseSensitive: false));
var assemblyPath = Path.GetDirectoryName(typeof(object).Assembly.Location);
// assemblyPath = "C:\Windows\Microsoft.NET\Framework64\v4.0.30319"
IEnumerable<MetadataReference> defaultReferences = new[]
{
MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "mscorlib.dll")),
MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.dll")),
MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.Core.dll")),
MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.Runtime.dll")),
MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.Xml.dll")),
MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.Data.dll"))
....
};
var defaultCompilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
.WithOverflowChecks(enabled: true).WithOptimizationLevel(OptimizationLevel.Debug);
var stream = new MemoryStream();
var compilation = await project.GetCompilationAsync();
var emitResult = CSharpCompilation.Create(
"test",
compilation.SyntaxTrees,
defaultReferences,
defaultCompilationOptions).Emit(stream);
来源:https://stackoverflow.com/questions/44473916/build-a-xamarin-project-via-roslyn-and-get-the-assembly