如何修复 C# Source Generators 未找到引用的问题

How to fix C# Source Generators Issue of not found references

我有这个项目使用 C# Source Generators。

https://github.com/efonsecab/PTIMicroservicesGenerators

我遇到的问题是我在编译控制台应用程序时遇到了这个问题

CSC : warning CS8785: Generator 'OpenApiClientServicesGenerator' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was of type 'FileNotFoundException' with message 'Could not load file or assembly 'Microsoft.OpenApi.Readers, Version=1.2.3.0, Culture=neutral, PublicKeyToken=3f5743946376f042' or one of its dependencies. The system cannot find the file specified.'

有人知道在使用 C# 源代码生成器时解决此问题的正确方法是什么吗? 感谢您的帮助。

问题是您没有部署所有依赖项。

将以下内容添加到您的 PTI.Microservices.Generators.csproj 项目文件

<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>

告诉 msbuild 将所有依赖项复制到输出目录。

我必须更改导入目录以镜像缓存目录:

<None Include="$(PkgNewtonsoft_Json)\lib\netstandard2.0\*.dll" Pack="true" PackagePath="/lib/netstandard2.0/" Visible="false" />

截至 2022 年 5 月,我相信您需要做的不仅仅是添加包参考:

在生成器项目文件中:

  1. 包引用必须有 GeneratePathProperty="true" PrivateAssets="all"
  2. 需要指定和配置GetTargetPathDependsOn

这条知识是基于看https://github.com/dotnet/roslyn-sdk/blob/main/samples/CSharp/SourceGenerators/SourceGeneratorSamples/CSharpSourceGeneratorSamples.csproj

  <ItemGroup>
    <!-- Generator dependencies -->
    <PackageReference Include="CsvTextFieldParser" Version="1.2.2-preview" GeneratePathProperty="true" PrivateAssets="all" />
  </ItemGroup>

  <PropertyGroup>
    <GetTargetPathDependsOn>$(GetTargetPathDependsOn);GetDependencyTargetPaths</GetTargetPathDependsOn>
  </PropertyGroup>

  <Target Name="GetDependencyTargetPaths">
    <ItemGroup>
      <TargetPathWithTargetPlatformMoniker Include="$(PKGCsvTextFieldParser)\lib\netstandard2.0\CsvTextFieldParser.dll" IncludeRuntimeDependency="false" />
    </ItemGroup>
  </Target>
</Project>