将T4输出保存到导入的程序集中的文件中

问题描述 投票:2回答:1

我正在尝试创建一个可导入文本模板的库,以使我的模板更易于使用。我的库的主要参数是模板对象。虽然这不是最佳做法,但我还没有找到可行的解决方法。一旦我在库中引用了模板对象,便试图将模板的输出保存到另一个位置。这是库的代码。

namespace Templates 
{
    public class Helper
    {
        private readonly object _thisTemplate = null;
        public Helper(object input) => _thisTemplate = input;

        public void SaveToFile(string path)
        {
            var transformTextMethod = _thisTemplate.GetType().GetMethod("TransformText");
            var content = transformTextMethod.Invoke(_thisTemplate, new object[] {}).ToString();

            using (System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Create))
            {
                using (System.IO.StreamWriter sr = new System.IO.StreamWriter(fs))
                {
                    sr.WriteLine(content);
                    sr.Flush();
                }
            }
        }
    }
}

这是我用来调用该库的模板

<#@ template debug="true" hostspecific="true" language="C#" #>
<#@ assembly name="$(ProjectDir)$(OutDir)$(TargetFileName)" #>
<#@ output extension="\\" #>
<#
    var helper = new Templates.Helper(this);
    var outputFile = this.Host.TemplateFile.Replace(".tt",".txt");
#>
<#= DateTime.Now.ToString() #>
<# helper.SaveToFile(outputFile); #>

模板具有<#@ output extension="\\" #>,因此不会产生任何输出,而是尝试使用SaveToFile方法保存它。当我尝试使用TextTemplatingFileGenerator运行它时,它使Visual Studio崩溃。为了获取更多信息,我尝试将其作为TextTemplatingFilePreProcessor运行,但是效果很好。

有人可以告诉我我在做什么错吗?

[我也接受了BurnsBA的建议,并修改了该模板以与TextTransform.exe配合使用,但是也会崩溃

作为一种解决方法,我在解决方案目录的模板文件夹中有一个基本模板,并在其中添加了这样的方法...

<#+
void SaveFile(string path)
{
    var content = this.GenerationEnvironment.ToString();

    using (System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Create))
    {  
        using (System.IO.StreamWriter str = new System.IO.StreamWriter(fs))
        {
            str.WriteLine(content.Trim("\n\r".ToCharArray()));
            str.Flush();
        }
    }
}
#> 

...,然后在我的模板顶部引用此基本模板,并包含如下所示的include伪指令...

<#@ include file="$(SolutionDir)Templates\BaseTemplate.ttinclude" #>

如果有人有任何想法,我仍然想找到一种可行的方法来在班级中保存此功能?

c# t4
1个回答
0
投票

您有无限循环...

TransformText中调用Helper.SaveToFile导致要评估的模板调用Helper.SaveToFile,该模板再次调用TransformText等,等等>

基类实现有效,因为您正在使用GenerationEnvironment属性,该属性不会再次评估模板。

© www.soinside.com 2019 - 2024. All rights reserved.