You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Standard 2.0源代码生成器加载System.Text.Json失败问题排查

.NET Standard 2.0源代码生成器加载System.Text.Json失败问题及临时解决方法

环境与项目配置

使用Visual Studio 2022 17.3.6版本,创建了一个.NET Standard 2.0的Source Generator项目,项目文件配置如下:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
    <IsRoslynComponent>true</IsRoslynComponent>
    <LangVersion>latest</LangVersion>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.CodeAnalysis" Version="4.3.1" />
    <PackageReference Include="System.Text.Json" Version="6.0.6" />
  </ItemGroup>
</Project>

已添加System.Text.Json 6.0.6的PackageReference,同时配置了调试用的Properties\launchSettings.json:

{
  "profiles": {
    "Profile 1": {
      "commandName": "DebugRoslynComponent",
      "targetProject": "..\\Enigma.GameWPF\\Enigma.GameWPF.csproj"
    }
  }
}

错误信息

点击Visual Studio中的运行调试按钮时,出现以下错误:

Could not load file or assembly 'System.Text.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or one of its dependencies. The system cannot find the file specified.

临时解决方法(2022年11月3日更新)

发现一个特殊的解决方式:

触发错误的原代码

[Generator]
public class SourceGenerator : IIncrementalGenerator {
    public void Initialize(IncrementalGeneratorInitializationContext context) {
        Generate(context);
    }

    public static void Generate(IncrementalGeneratorInitializationContext context) {
        var names = context.AdditionalTextsProvider
            .Where(static at => at.Path.EndsWith("JsonFile.json"))
            .SelectMany(static (at, _) => {
                JsonDocument jsonDocument = JsonDocument.Parse(at.GetText(_).ToString());
                return jsonDocument.RootElement.EnumerateArray();
            })
            .Select(static (je, _) => je.GetProperty("GeneratedClassName").GetString());

        context.RegisterSourceOutput(names, static (context, name) => {
            string sourceCode = $@"
public class {name}{{
}}
";
            context.AddSource(name + ".g.cs", sourceCode);
        });
    }
}

解决问题的修改后代码

将Generate方法内联到Initialize方法中即可解决加载错误:

[Generator]
public class SourceGenerator : IIncrementalGenerator {
    public void Initialize(IncrementalGeneratorInitializationContext context) {
        var names = context.AdditionalTextsProvider
            .Where(static at => at.Path.EndsWith("JsonFile.json"))
            .SelectMany(static (at, _) => {
                JsonDocument jsonDocument = JsonDocument.Parse(at.GetText(_).ToString());
                return jsonDocument.RootElement.EnumerateArray();
            })
            .Select(static (je, _) => je.GetProperty("GeneratedClassName").GetString());

        context.RegisterSourceOutput(names, static (context, name) => {
            string sourceCode = $@"
public class {name}{{
}}
";
            context.AddSource(name + ".g.cs", sourceCode);
        });
    }
}

内容的提问来源于stack exchange,提问作者martinrhan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 08:50:25