T4テンプレートを処理できるアプリケーションを実装しようとしています。T4テンプレートパラメータディレクティブを使用する場合のNullReferenceException
この記事で示したように、私は、カスタムテキストテンプレートホストを実装している: 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);
私は、パラメータ値がエンジンに転送されることはありませんと思われるので、質問は次のとおりです。
私は転送するにはどうすればよいですパラメータ値をエンジンに送信しますか?
host.Initialize();
を使用するthis questionが見つかりましたが、それはプリコンパイルされたテンプレートのようであり、例の記事では実装されていません。また、その記事に記載されているとおり、CreateSession();
も実装されていません。
P.S. 記事のコードを機能させるために、Microsoft.VisualStudio.TextTemplating.15.0
とMicrosoft.VisualStudio.TextTemplating.Interfaces.15.0
への参照を追加するだけでなく、NugetパッケージMicrosoft.CodeAnalysis
を追加する必要がありました。
私はVS2017を使用しています。ターゲットフレームワーク:.Net Framework 4.6.2
優れている必要があります。それを解決したITextTemplatingSessionHostがありませんでした。 ありがとうございました。 – TechnoCowboy