【发布时间】:2017-11-07 16:58:52
【问题描述】:
我正在尝试实现一个可以处理 T4 模板的应用程序。
我已经实现了一个自定义文本模板主机,如本文所示: https://msdn.microsoft.com/en-us/library/bb126579.aspx
我可以像这样运行一个简单的模板,它适用于 C# 代码和 include 指令:
<#@ template debug="true" #>
<#@ include file="includehello.txt" #>
Some text.
<# for(int i = 0; i < 3; i++) { #>
//Line <#= i #>
<# } #>
但是,一旦我尝试使用“参数”指令,我就会得到 NullReferenceException。
<#@ template debug="true" #>
<#@ parameter type="System.String" name="worldParam" #>
Hello <#=worldParam#>
运行模板的代码如下所示:
CustomCmdLineHost host = new CustomCmdLineHost();
Engine engine = new Engine();
host.TemplateFileValue = "HelloWorldTemplate.tt";
//Read the text template.
string input = File.ReadAllText(templateFileName);
host.Session = host.CreateSession();
// Add parameter values to the Session:
host.Session["worldParam"] = "world";
//Transform the text template.
string output = engine.ProcessTemplate(input, host);
//Save the result
string outputFileName = Path.GetFileNameWithoutExtension(templateFileName);
outputFileName = Path.Combine(Path.GetDirectoryName(templateFileName), outputFileName);
outputFileName = outputFileName + "1" + host.FileExtension;
File.WriteAllText(outputFileName, output, host.FileEncoding);
我怀疑参数值从来没有传入引擎,所以问题是:
如何将参数值传输到引擎?
我发现this question 使用了host.Initialize();,但这似乎是用于预编译的模板,并且示例文章中没有实现Initialize 方法。我实现的 CreateSession(); 也不是那篇文章中描述的。
附:
为了使文章中的代码能够正常工作,我必须添加 Nuget 包 Microsoft.CodeAnalysis,此外还要添加提到的对 Microsoft.VisualStudio.TextTemplating.15.0 和 Microsoft.VisualStudio.TextTemplating.Interfaces.15.0 的引用。
我正在使用 VS2017。目标框架:.Net Framework 4.6.2
【问题讨论】:
标签: c# visual-studio-2017 t4