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

Mac下编译T4文本模板求助:遇System.Text.Json程序集引用解析错误

在Mac环境编译T4文件的可行方案

方案1:用.NET CLI工具手动编译

微软提供了Microsoft.TemplateEngine.T4工具包,可通过命令行完成T4编译:

  1. 全局安装T4工具:
    dotnet tool install -g dotnet-t4
    
  2. 终端导航到T4文件目录,执行编译命令时手动指定System.Text.Json的本地路径(替换为你实际的.NET版本路径):
    t4 your-template.tt -r "/usr/local/share/dotnet/shared/Microsoft.NETCore.App/[你的.NET版本号]/System.Text.Json.dll"
    
    示例:.NET 6.0的路径可能是/usr/local/share/dotnet/shared/Microsoft.NETCore.App/6.0.25/System.Text.Json.dll

方案2:自定义C#脚本编译

创建CompileT4.csx脚本,借助Roslyn处理T4模板及引用:

using Microsoft.VisualStudio.TextTemplating;
using Microsoft.VisualStudio.TextTemplating.VSHost;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

var templatePath = "your-template.tt";
var outputPath = "output.cs";

var engine = new Engine();
var host = new CustomHost();
// 添加System.Text.Json引用
host.AddAssemblyReference(typeof(System.Text.Json.JsonSerializer).Assembly.Location);

var result = engine.ProcessTemplate(File.ReadAllText(templatePath), host);
File.WriteAllText(outputPath, result);

class CustomHost : ITextTemplatingEngineHost
{
    private readonly List<string> _references = new();

    public void AddAssemblyReference(string reference) => _references.Add(reference);

    public string ResolveAssemblyReference(string assemblyReference)
    {
        return _references.FirstOrDefault(r => r.EndsWith(assemblyReference)) ?? assemblyReference;
    }

    public string ResolvePath(string path) => Path.GetFullPath(path);
    public string GetHostOption(string optionName) => string.Empty;
    public object GetService(Type serviceType) => null;
    public IList<string> StandardAssemblyReferences => new List<string>();
    public IList<string> StandardImports => new List<string>();
    public string TemplateFile => string.Empty;
    public void LogErrors(CompilerErrorCollection errors) {}
    public AppDomain ProvideTemplatingAppDomain(string content) => AppDomain.CurrentDomain;
}

执行脚本:

dotnet script CompileT4.csx

方案3:换用JetBrains Rider

Mac版JetBrains Rider原生支持T4模板的编辑与编译,能自动识别处理System.Text.Json这类.NET程序集引用,无需额外配置。

针对System.Text.Json引用错误的补充提示

  • 确保项目目标框架为.NET Core 3.0及以上(System.Text.Json从该版本开始内置)
  • 若使用.NET Framework,需先安装System.Text.Json NuGet包,并在T4模板中明确引用:
    <#@ assembly name="System.Text.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51" #>
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 16:42:27