我有一个我正在尝试创建的 T4 模板,它将通过 Nhibernate 对数据库中的 gen 查找值进行编码。我的问题是我的数据访问层使用 Nhibernate 配置的路径以便在启动时编译配置(静态构造函数)。
我不知道如何让 t4 “看到”这个文件路径,以便当我的代码生成运行时它可以获得这个配置文件。我也不知道如何让 t4 “看到”我的配置管理器类;其中包含列出 nhibernate xml 文件路径的应用程序设置。
我有两个配置文件,一个用于 SQL Server,一个用于 sqlite。配置文件需要在执行程序集的根目录中才能休眠编译配置。
看来我的模板将无法使用高级业务层从数据库中选择数据,而是我可能不得不将所有的 nhibernate 配置代码也复制到模板中(呃)。
我的数据库包装器:
private class DBSingleton
{
static DBSingleton()
{
string path = ConfigurationManager.AppSettings["DBConfigFileFullPath"];
NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration().Configure(path);
cfg.AddInputStream(HbmSerializer.Default.Serialize(System.Reflection.Assembly.GetAssembly(typeof(Plan))));
instance = cfg.BuildSessionFactory();
}
internal static readonly ISessionFactory instance;
}
还有我的模板:
<#
System.Diagnostics.Debugger.Launch();
string path = Host.ResolvePath(@"..\DB.UnitTest\App.config");
System.Configuration.ConfigurationManager.AppSettings.Add(
"DBConfigFileFullPath", path);
//System.Configuration.ConfigurationFileMap fileMap = new ConfigurationFileMap(path); //Path to your config file
//System.Configuration.Configuration configuration = System.Configuration.ConfigurationManager.OpenMappedMachineConfiguration(fileMap);
ReferenceValueBL bl = new ReferenceValueBL();
List<ReferenceValue> refVals = bl.Select(); <- problem occurs here
foreach(ReferenceValue rv in refVals)
{
Write("Public ");
Write(rv.ReferenceValueCode.GetType().Name);
Write(" ");
Write(rv.ReferenceValueCode);
Write(" = ");
Write(rv.ReferenceValueCode);
}
#>
当 bl 变量尝试调用 select() 时,就会出现我的问题。那是初始化 DBSingleton 的时候。它抛出一个错误,说应用程序设置为空。如果我将 DB 类中的相对文件路径硬编码为 ./Dbconfig.xml 它仍然会引发错误,因为执行程序集的本地目录中没有该文件。
其他人如何处理让 t4 使用 app/web 配置文件而不从模板中读取配置文件然后将连接字符串注入(inject) DAL?我没有那种奢侈。该文件必须放在可读的位置,或者 t4 必须知道在某处查找。
最佳答案
How do other people handle getting t4 to use app/web config files without reading from the config file within the template and then injecting a connection string into the DAL?
您或许可以将您的文本模板转换为 runtime text template通过设置属性 | “TextTemplatingFilePreprocessor”的自定义工具。
之后,整个代码生成过程将被封装在标准类中,该类将具有
TransformText
产生结果字符串的方法 - 然后您可以将其写入您喜欢的文件中。好的是模板类是部分的,所以你可以添加一些自定义方法的实现。可能是这样的:
public partial class RuntimeTextTemplate1
{
public string TransformText(string someParameter)
{
// Do something with someParameter, initialize class field
// with its value and later use this field in your t4 file.
// You also have access to ConfigurationManager.AppSettings here.
return TransformText();
}
}
另外,这个:
foreach(ReferenceValue rv in refVals)
{
Write("Public ");
Write(rv.ReferenceValueCode.GetType().Name);
Write(" ");
Write(rv.ReferenceValueCode);
Write(" = ");
Write(rv.ReferenceValueCode);
}
可以改写为:
foreach(ReferenceValue rv in refVals)
{
#>
Public <#= rv.ReferenceValueCode.GetType().Name #> <#= rv.ReferenceValueCode #> = <#= rv.ReferenceValueCode #>
<#+
}
关于nhibernate - 创建 T4 模板时,如何利用应用配置和其他文件资源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11729888/