2016-07-23 15 views
0

T4テンプレート内でSystem.Configurationアセンブリを使用して、プロジェクトのApp.configにリストされている接続文字列を取得したいとします。ただし、コンパイラはステートメントブロック内の[]を受け入れていないようです。これはどうですか?T4テンプレートステートメントブロックの角括弧の構文

<#@ assembly name="System.Configuration" #> 
<#@ import namespace="System.Configuration"#> 

<# 

    var connectionString = ConfigurationManager.ConnectionStrings["localconnection"].ConnectionString; 

#> 

TIA

+0

どのようなエラーが表示されますか? – AlexP

+0

おそらく、[how-to-make-connection-strings-t4-template-in-t4-template]の複製(http://stackoverflow.com/questions/25460348/how-to-make-connection-strings-available -in-a-t4-template) – AlexP

+0

@AlexP返事が遅れて申し訳ありません。 tmpファイルのいくつかの調査では、[]文字列が正しくコンパイルされていることがわかりましたが、構成マネージャーはプロジェクトのApp.configで接続文字列を見ていないので、 "null"が返されていました。すべての接続文字列をループすると、コンソールプロジェクトに固有のデフォルトのmachine.config接続文字列だけが見つかります。 :((VS 2015)これに関する任意のガイダンスありがとう(私はこの質問を書く前にあなたのリンクを適用し、それは動作しませんでした:()。 –

答えて

1

あなたがデザイン時にT4実行している場合(CustomTool:TextTemplatingFilePreprocessor)は、テンプレートコードは、VisualStudioをプロセスの一部として実行されます。 VisualStudioはdevenv.exe.configをロードしていて、プロジェクトの設定はロードしていません(AppDomain.CurrentDomain.SetupInformation.ConfigurationFileで確認できます)。

これで、null ref例外が発生します。 - 'localconnection'接続文字列はdevenv.exe.configにありません。あなたはConfigurationManager.OpenMappedExeConfigurationを使用してプロジェクトの設定ファイルを読み込むことができ

<#@ template debug="false" hostspecific="true" language="C#" #> 
<#@ assembly name="System.Configuration" #> 
<#@ import namespace="System.Configuration"#> 
<#@ import namespace="System.IO" #> 

<# 
    string configPath = Path.Combine(Host.ResolveAssemblyReference("$(ProjectDir)"), "App.config"); 
    var configFileMap = new ExeConfigurationFileMap{ExeConfigFilename = configPath};  

    var config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None); 
    string connectionString = config.ConnectionStrings.ConnectionStrings["localconnection"].ConnectionString; 

    WriteLine(connectionString); 
#> 

注意を、それはあなたのプロジェクトフォルダを解決するために、ホストを使用するためにhostspecific =「true」をする必要があります。