因项目需要,需要动态生成netcore代码。 研究一下午,终于尝试成功。
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Text;
using Microsoft.Extensions.DependencyModel;
using System;
using System.Diagnostics.Metrics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Metadata;
using System.Runtime.Loader;
using System.Text;
using static System.Net.Mime.MediaTypeNames;
public static void Test()
{
var code = @"
using System;
public class MyClass
{
public static void MyMethod(int value)
{
}
}";
//
var host = MefHostServices.Create(MefHostServices.DefaultAssemblies);
//创建工程文件
var workspace = new AdhocWorkspace(host);
//创建projectid,在创建文档是需要使用
var projectid = ProjectId.CreateNewId();
//创建文档id
var documentId = DocumentId.CreateNewId(projectid);
//创建文档信息
var documentInfo = DocumentInfo.Create(documentId, "MyFile.cs",
loader: TextLoader.From(TextAndVersion.Create(SourceText.From(code, Encoding.UTF8), VersionStamp.Create())));
//创建工程
var projectInfo = ProjectInfo.Create(
projectid,
VersionStamp.Create(),
"MyProject123",
"MyProject123",
LanguageNames.CSharp,
null,
null,
//使用dll
new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
)
//添加文档
.WithDocuments(new[] { documentInfo })
//添加引用
.WithMetadataReferences(new[]
{
MetadataReference.CreateFromFile(typeof(object).Assembly.Location)
});
//创建工程
var project = workspace.AddProject(projectInfo);
//编译工程
var compilation = project.GetCompilationAsync().Result;
//将dll提取到文件
var compilationResult = compilation.Emit(".\\outputdll\\" + projectInfo.AssemblyName + ".dll");
//提取失败,提示异常信息
if (!compilationResult.Success)
{
foreach (Diagnostic codeIssue in compilationResult.Diagnostics)
{
string issue = $"ID: {codeIssue.Id}, Message: {codeIssue.GetMessage()},Location: {codeIssue.Location.GetLineSpan()},Severity: {codeIssue.Severity}";
System.Console.WriteLine(issue);
}
}
}
引用
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Features" Version="4.7.0" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="4.7.0" />
</ItemGroup>
生成的dll在netcore环境下引用成功!