简体   繁体   English

使用Roslyn CSharpCompilation生成.NET Standard 2.0 DLL

[英]Generate .NET Standard 2.0 DLL using Roslyn CSharpCompilation

I am working on a service which, given a URL to a Swagger definition, uses NSwag to generate a C# Proxy for the Service. 我正在开发一项服务,该服务使用Swagger定义的URL,使用NSwag为该服务生成C#代理。 The entire proxy is contained within a single C# file. 整个代理都包含在单个C#文件中。

I would like to automate compilation of the generated code into a .NET Standard 2.0 DLL using Roslyn. 我想使用Roslyn将生成的代码自动编译成.NET Standard 2.0 DLL。 This should be done in-memory, using the CSharpCompilation class. 这应该使用CSharpCompilation类在内存中完成。

To confirm that this is possible, I have created a .NET Standard 2.0 class library project in Visual Studio 2017 and added NuGet dependencies for Newtonsoft.Json (10.0.3) and System.ComponentModel.Annotations (4.4.0). 为了确认这是可能的,我在Visual Studio 2017中创建了一个.NET Standard 2.0类库项目,并为Newtonsoft.Json(10.0.3)和System.ComponentModel.Annotations(4.4.0)添加了NuGet依赖项。 I can see that the project type also brings in an SDK dependency on NETStandard.Library. 我可以看到该项目类型还引入了对NETStandard.Library的SDK依赖关系。

I understand that I will not use a project file to generate the DLL with Roslyn, however, I am struggling to figure out the equivalent steps to take to generate the same DLL. 我知道我不会使用项目文件来与Roslyn生成DLL,但是,我正在努力找出生成相同DLL所要采取的等效步骤。

The key to building a .NET Standard DLL was selecting the correct DLLs to add as MetadataReference objects. 建立.NET标准DLL的关键是选择正确的DLL添加为MetadataReference对象。 It was not initially clear to me what these were because the Visual Studio 2017 .csproj format does not explicitly reference the them. 我最初不清楚这些是什么,因为Visual Studio 2017 .csproj格式未明确引用它们。

I was able to download the NuGet package for netstandard.library and loop through the contents, adding each DLL inside as a MetadataReference. 我能够下载netstandard.library的NuGet包,并循环浏览内容,将每个DLL添加为MetadataReference。 I believe that this achieves the same goal as adding a .csproj SDK dependency on NetStandard.Library. 我相信,这可以达到与在NetStandard.Library上添加.csproj SDK依赖项相同的目标。

With the addition of these references, I was able to compile my generated code. 通过添加这些引用,我能够编译生成的代码。 I tested my output assembly by referencing it from a .NET Core 2.0 Console Application. 我通过从.NET Core 2.0控制台应用程序引用输出程序集来对其进行测试。

There may be an easier way to do this - I'd be happy to hear it! 可能有一种更简单的方法-我很高兴听到它!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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