Nhibernate 创建T4模板时,如何利用应用程序配置和其他文件资源?

Nhibernate 创建T4模板时,如何利用应用程序配置和其他文件资源?,nhibernate,t4,Nhibernate,T4,我有一个T4模板,我正在尝试创建它,它将通过Nhibernate从数据库编码gen查找值。我的问题是,我的数据访问层使用Nhibernate配置的路径,以便在启动时编译配置(静态构造函数) 我不知道如何使t4“查看”此文件路径,以便在我的代码生成器运行时可以获取此配置文件。我也不知道如何使t4“看到”我的configuration manager类;其中包含列出nhibernate xml文件路径的应用程序设置 我有两个配置文件,一个用于SQLServer,一个用于sqlite。配置文件需要位于

我有一个T4模板,我正在尝试创建它,它将通过Nhibernate从数据库编码gen查找值。我的问题是,我的数据访问层使用Nhibernate配置的路径,以便在启动时编译配置(静态构造函数)

我不知道如何使t4“查看”此文件路径,以便在我的代码生成器运行时可以获取此配置文件。我也不知道如何使t4“看到”我的configuration manager类;其中包含列出nhibernate xml文件路径的应用程序设置

我有两个配置文件,一个用于SQLServer,一个用于sqlite。配置文件需要位于执行程序集的根目录中,以便nhibernate编译配置

我的模板似乎无法使用高级业务层从数据库中选择数据,相反,我可能还必须将所有nhibernate配置代码复制到模板中(ugh)

我的数据库包装器:

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);
}

#>

其他人如何处理让t4使用app/web配置文件而不读取模板中的配置文件,然后将连接字符串注入DAL

您可以通过将Properties | Custom Tool设置为“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 #>
<#+
}
foreach(参考值中的参考值rv)
{
#>
公开的=