Mac下编译T4文本模板求助:遇System.Text.Json程序集引用解析错误
在Mac环境编译T4文件的可行方案
方案1:用.NET CLI工具手动编译
微软提供了Microsoft.TemplateEngine.T4工具包,可通过命令行完成T4编译:
- 全局安装T4工具:
dotnet tool install -g dotnet-t4 - 终端导航到T4文件目录,执行编译命令时手动指定
System.Text.Json的本地路径(替换为你实际的.NET版本路径):
示例:.NET 6.0的路径可能是t4 your-template.tt -r "/usr/local/share/dotnet/shared/Microsoft.NETCore.App/[你的.NET版本号]/System.Text.Json.dll"/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.JsonNuGet包,并在T4模板中明确引用:<#@ assembly name="System.Text.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51" #>
内容的提问来源于stack exchange,提问作者Funky Sloth
相关产品推荐
相关产品推荐

