使用 Roslyn 编译 .NET Core 应用 API

Compiling .NET Core App with Roslyn API

我正在生成一些动态 C# 并想将其编译为 .NET Core 应用程序。但是,似乎缺少 deps.json 文件以使其实际可运行。 所以编译本身是有效的,但是在 运行 dotnet [name of dll] 上它给出了一个错误:

在我的代码中

  CSharpCompilation compilation = CSharpCompilation.Create(assemblyName,
    syntaxTrees: files,
    references: references,
    options: new CSharpCompilationOptions(OutputKind.ConsoleApplication,
      optimizationLevel: OptimizationLevel.Debug
    )
  );

  FileUtility.CreateDirectory(outputDllPath);
  EmitResult result = compilation.Emit(outputDllPath, pdbPath: outputPdbPath);

引用集合包含 Microsoft.NETCore.App 和 netstandard 2.0.0 ref dll,以及其他符合 netstandard2.0 的特定 dll。

这没有错误。在 运行 我得到:

Unhandled Exception: System.TypeLoadException: Could not load type 'System.Object' from assembly 'netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'.

如何为我的编译生成正确的 deps.json 文件?

我们通过执行以下操作解决了它:

根据 C:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.netcore.app.0.0\ref\netcoreapp2.0 中的 dll 编译 C# 文件(不要添加对 .NET 4. dll 的引用!):

public static IEnumerable<PortableExecutableReference> CreateNetCoreReferences()
{
  foreach(var dllFile in Directory.GetFiles(@"C:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.netcore.app.0.0\ref\netcoreapp2.0", "*.dll"))
  {
    yield return MetadataReference.CreateFromFile(dllFile);
  }
}

使用 ConsoleApp 作为输出创建 CSharpCompilation

CSharpCompilation.Create(assemblyName,
    syntaxTrees: files,
    references: references,
    options: new CSharpCompilationOptions(OutputKind.ConsoleApplication)
  );

现在只需要在输出的旁边加上runtimeconfig.json([dllname].runtimeconfig.json),内容如下:

{
  "runtimeOptions": {
    "tfm": "netcoreapp2.0",
    "framework": {
      "name": "Microsoft.NETCore.App",
      "version": "2.0.0"
    }
  }
}

输出可以是 运行 和 dotnet.exe。