无法创建 C# 源代码生成器

C# Source Generator cannot be created

我自己和我的同事在过去几周的某个时候都开始看到这个问题:

Build FAILED

CSC : warning CS8032: An instance of analyzer My.Company.Generators.ReportingV2Generator cannot be created from /Users/work/dev/git/reporting-model/src/My.Company.Generators/bin/Debug/netstandard2.1/My.Company.Generators.dll : Could not load file or assembly 'Microsoft.CodeAnalysis, Version=3.10.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'. The system cannot find the file specified.. [/Users/work/dev/git/reporting-model/src/My.Team.Models.ReportingV2/My.Team.Models.ReportingV2.csproj]

/Users/work/dev/git/reporting-model/src/My.Company.Api/SmokeTests/Tests/ContentAskExpertSmokeTest.cs(7,20): error CS0234: The type or namespace name 'Models' does not exist in the namespace 'My.Team' (are you missing an assembly reference?) [/Users/work/dev/git/reporting-model/src/My.Company.Api/My.Company.Api.csproj]
... Many more of the above "type or namespace" errors
...

这在 macOS 和 Windows 上都会发生。它在 Linux 上工作(在个人机器上和 mcr.microsoft.com/dotnet/sdk:5.0.

内部

字面上 none 源代码生成器代码 / csproj 已更改,大约两周前自发启动。我也可以在两个月前的提交中重现它,所以看起来包中的某些东西可能在外部发生了变化?

我通过直接访问 Microsoft 找到了解决方案。

The error on the failure case is that the generator is dependent on Microsoft.CodeAnalysis.dll version 3.10, and 3.10 only shipped in 5.0.300. It appears that your success case is using SDK 5.0.300 but the failure case is using 5.0.204.

You have two options to fix this:

If you're not using any of the features introduced in 3.10 for source generators, you can lower the Microsoft.CodeAnalysis nuget package target to 3.9 Ensure that all builds are using at least 5.0.300 version of the SDK

https://github.com/dotnet/roslyn/issues/54710