使用参数指令时 T4 模板 NullReferenceException

T4 template NullReferenceException when using parameter directive

我正在尝试实现一个可以处理 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 #>
    <# } #>

但是,一旦我尝试使用 "parameter" 指令,我就会收到 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(); 我按照那篇文章中的描述实现了它。

P.S。 为了让文章中的代码正常工作,除了添加提到的对 Microsoft.VisualStudio.TextTemplating.15.0Microsoft.VisualStudio.TextTemplating.Interfaces.15.0.

的引用之外,我还必须添加 Nuget 包 Microsoft.CodeAnalysis

我正在使用 VS2017。目标框架:.Net Framework 4.6.2

除了 ITextTemplatingEngineHost 之外,您还需要实现 ITextTemplatingSessionHost 接口。 Class签名必须是

public class CustomCmdLineHost : ITextTemplatingEngineHost, ITextTemplatingSessionHost