【问题标题】:Build fails because of System.Text.Json generated code由于 System.Text.Json 生成的代码,构建失败
【发布时间】:2022-07-28 20:39:44
【问题描述】:

我正在使用 System.Text.Json(版本 6.0.5)的源代码生成。

我的代码如下所示。

[JsonSerializable(typeof(AuthenticationToken))]
[JsonSerializable(typeof(AuthenticationData))]
[JsonSerializable(typeof(ApplicationSettings))]
[JsonSerializable(typeof(Refit.ProblemDetails))]
// (...)
public partial class JsonContext : JsonSerializerContext
{
}

// (...)
private static JsonSerializerOptions GetDefaultOptions()
{
    var options = new JsonSerializerOptions();
    options.AddContext<JsonContext>();

    return options;
}

此代码位于 NetStandard2.0 库中。除了项目和包引用,csproj 只包含以下属性。

<PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
    <LangVersion>9.0</LangVersion>
</PropertyGroup>

此代码可在本地发布和调试配置以及 Visual Studio 2022 和 2019 中使用。

问题

当我在 CI 管道中构建相同的代码时,会产生以下错误。

##[error]C:\WIN1809-01\_work\11\s\src\app\ApplicationTemplate.Presentation\System.Text.Json.SourceGeneration\System.Text.Json.SourceGeneration.JsonSourceGenerator\JsonContext.g.cs(10,6): Error CS0579: Duplicate 'global::System.CodeDom.Compiler.GeneratedCodeAttribute' attribute
##[error]C:\WIN1809-01\_work\11\s\src\app\ApplicationTemplate.Presentation\System.Text.Json.SourceGeneration\System.Text.Json.SourceGeneration.JsonSourceGenerator\JsonContext.Type.g.cs(11,100): Error CS0102: The type 'JsonContext' already contains a definition for '_Type'
##[error]C:\WIN1809-01\_work\11\s\src\app\ApplicationTemplate.Presentation\System.Text.Json.SourceGeneration\System.Text.Json.SourceGeneration.JsonSourceGenerator\JsonContext.Type.g.cs(12,98): Error CS0102: The type 'JsonContext' already contains a definition for 'Type'
##[error]C:\WIN1809-01\_work\11\s\src\app\ApplicationTemplate.Presentation\System.Text.Json.SourceGeneration\System.Text.Json.SourceGeneration.JsonSourceGenerator\JsonContext.String.g.cs(11,102): Error CS0102: The type 'JsonContext' already contains a definition for '_String'
##[error]C:\WIN1809-01\_work\11\s\src\app\ApplicationTemplate.Presentation\System.Text.Json.SourceGeneration\System.Text.Json.SourceGeneration.JsonSourceGenerator\JsonContext.String.g.cs(12,100): Error CS0102: The type 'JsonContext' already contains a definition for 'String'

这些只是前几行。实际上有大约 200 行类似的错误,都源自JsonContext.xxx.g.cs 生成的文件。

这是一个已知问题吗?我只是缺少一些配置吗?

【问题讨论】:

    标签: c# azure-pipelines system.text.json


    【解决方案1】:

    解决方法

    我找到了解决方法。

    基本上,我有多个代表应用程序层的程序集:

    DAL -> Business -> Presentation
    

    我将我的代码(JsonContext 声明)从 Presentation 程序集移动到 DAL 程序集,它现在可以工作了。

    我不明白为什么会这样,但是如果您发现自己遇到类似问题,这也可能对您有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-29
      • 2015-08-12
      • 1970-01-01
      • 2011-12-18
      • 2022-01-07
      • 2020-12-02
      • 1970-01-01
      • 2017-01-16
      相关资源
      最近更新 更多