Add module as reference in Roslyn

馋奶兔 提交于 2019-12-11 07:10:45

问题


I'm trying to implement following csc command based compilation with the Roslyn Microsoft.Codeanalysis library

csc /target:library /out:UserControlBase.dll UserControlBase.cs /addmodule:"c:\artifacts\MyLib.netmodule"

Following is the implementation of the same with Roslyn

var compilation = await project.GetCompilationAsync();
//Add Module
compilation.AddReferences(ModuleMetadata.CreateFromFile(@"c:\artifacts\MyLib.netmodule").GetReference());
compilationStatus = compilation.Emit(outputFolderPath + @"\Test1.dll", outputFolderPath + @"\Test1.pdb");
if (!compilationStatus.Success)
{
    foreach (var item in compilationStatus.Diagnostics)
    {
        Console.WriteLine(item);
    }
}

Issue: .Netmodule is not getting added to the project and compilation failed due to references not resolved from netmodule.

Does anyone know the correct way to add this?

I'm using Microsoft.CodeAnalysis 1.0.0


回答1:


I know this is a little old, but the answer could be useful to someone else.

Everything in Roslyn is immutable. So, calling compilation.AddReference doesn't add the reference to the compilation object you have, but instead creates a new compilation object based on the original, with the additional references.

so, for this to work you need to call Emit in the object returned by the AddReference call. You could just replace the compilation variable:

compilation = compilation.AddReferences(ModuleMetadata.CreateFromFile(@"c:\artifacts\MyLib.netmodule").GetReference());

or use a new variable and call Emit from that:

var compWithRefs = compilation.AddReferences(ModuleMetadata.CreateFromFile(@"c:\artifacts\MyLib.netmodule").GetReference());
compilationStatus = compWithRefs.Emit(outputFolderPath + @"\Test1.dll", outputFolderPath + @"\Test1.pdb");


来源:https://stackoverflow.com/questions/46825603/add-module-as-reference-in-roslyn

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