简体   繁体   中英

Add module as reference in Roslyn

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

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM