Build a Xamarin project via Roslyn and get the assembly

十年热恋 提交于 2019-12-11 07:38:58

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!