Share via


T4 テキスト テンプレートから Visual Studio またはその他のホストへのアクセス

更新 : 2011 年 3 月

テキスト テンプレートでは、テンプレートを実行するホスト (Visual Studio など) によって公開されるメソッドとプロパティを使用できます。

これは、前処理されたテキスト テンプレートではなく、標準のテキスト テンプレートに当てはまります。

ホストへのアクセスの取得

template ディレクティブで hostspecific="true" を設定します。 これにより、ITextTemplatingEngineHost 型の this.Host を使用できるようになります。 この型は、ファイル名の解決やエラー ログの記録などに使用できるメンバーを持ちます。

ファイル名の解決

テキスト テンプレートに関連するファイルの完全パスを確認するには、this.Host.ResolvePath() を使用します。

<#@ template hostspecific="true" language="C#" #>
<#@ output extension=".txt" #>
<#@ import namespace="System.IO" #>
<#
 // Find a path within the same project as the text template:
 string myFile = File.ReadAllText(this.Host.ResolvePath("MyFile.txt"));
#>
Content of myFile is:
<#= myFile #>

エラー メッセージの表示

この例では、テンプレートの変換時にメッセージ ログを記録します。 ホストが Visual Studio の場合は、エラー ウィンドウにメッセージ ログが追加されます。

<#@ template hostspecific="true" language="C#" #>
<#@ output extension=".txt" #>
<#@ import namespace="System.CodeDom.Compiler" #>
<#
  string message = "test message";
  this.Host.LogErrors(new CompilerErrorCollection() 
    { new CompilerError(
       this.Host.TemplateFile, // Identify the source of the error.
       0, 0, "0",   // Line, column, error ID.
       message) }); // Message displayed in error window.
#>

Visual Studio API の使用

Visual Studio でテキスト テンプレートを実行する場合は、this.Host を使用して、Visual Studio によって提供されるサービスと、読み込まれたパッケージまたは拡張機能にアクセスできます。

hostspecific="true" を設定し、this.Host を IServiceProvider にキャストします。

この例では、Visual Studio API である DTE をサービスとして取得します。

<#@ template hostspecific="true" language="C#" #>
<#@ output extension=".txt" #>
<#@ assembly name="EnvDTE" #>
<#@ import namespace="EnvDTE" #>
<# 
 IServiceProvider serviceProvider = (IServiceProvider)this.Host;
 DTE dte = serviceProvider.GetService(typeof(DTE)) as DTE;  
#>
Number of projects in this solution: <#=  dte.Solution.Projects.Count #>

履歴の変更

日付

履歴

理由

2011 年 3 月

トピックが作成されました。

カスタマー フィードバック