C# T4使用参数指令时模板NullReferenceException

C# T4使用参数指令时模板NullReferenceException,c#,visual-studio-2017,t4,C#,Visual Studio 2017,T4,我正在尝试实现一个可以处理T4模板的应用程序 我已经实现了一个自定义文本模板主机,如本文所示: 我可以运行这样一个简单的模板,它可以很好地与C#代码和include指令配合使用: <#@ template debug="true" #> <#@ include file="includehello.txt" #> Some text. <# for(int i = 0; i < 3; i++) { #>

我正在尝试实现一个可以处理T4模板的应用程序

我已经实现了一个自定义文本模板主机,如本文所示:

我可以运行这样一个简单的模板,它可以很好地与C#代码和include指令配合使用:

    <#@ template debug="true" #>
    <#@ include file="includehello.txt" #>  
    Some text.
    <# for(int i = 0; i < 3; i++) { #>
        //Line <#= i #>
    <# } #>
我怀疑参数值从未传输到发动机中,因此问题是:

如何将参数值传输到发动机

我发现它使用
host.Initialize()但这似乎是针对预编译模板的,示例文章中没有实现
Initialize
方法。
CreateSession()也不是我按照那篇文章中的描述实现了它

附言。 为了使文章中的代码正常工作,我必须添加Nuget包
Microsoft.CodeAnalysis
,此外还要添加对
Microsoft.VisualStudio.TextTemplating.15.0
Microsoft.VisualStudio.TextTemplating.Interfaces.15.0
的引用


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

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

public class CustomCmdLineHost : ITextTemplatingEngineHost, ITextTemplatingSessionHost

杰出的是丢失的ITextTemplatingSessionHost解决了此问题。非常感谢你的帮助。
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);
public class CustomCmdLineHost : ITextTemplatingEngineHost, ITextTemplatingSessionHost