【发布时间】:2014-12-28 03:09:06
【问题描述】:
我们有一种情况,我们基本上想通过传入模板内容的参数和模板自己构建所需的信息来生成代码文件的字符串表示:
//*** PSEUDO CODE *** //
//loaded from an embedded resource file in a .dll. no physical file on file system
string templateContents = ...;
//has properties used by the template
object complexParameter = ...;
string generatedCode = generator.MakeCode(templateContents, complexParameter);
但是,我们目前在尝试使 T4 模板生成执行我们想要的操作时遇到了问题。我们使用的实际代码是:
var templatingEngine = new Engine();
//T4TextTemplateHost is our own class implementing ITextTemplatingEngineHost & IServiceProvider
var templateHost = new T4TextTemplateHost(references, imports)
{
Properties = parameters,
//this is supposed to be a file path? the generation bombs if this is left null
TemplateFile = "Dummy Value"
};
var templateContents = GetTemplateFileContents();
var retVal = templatingEngine.ProcessTemplate(templateContents, templateHost);
//if a CompilerError occurs, we get NO code, just a "ErrorGeneratingOutput" message
foreach (CompilerError error in templateHost.Errors)
//this information is pretty worthless: a compile error with line number for a
//non-existant code file
retVal += String.Format("{0}{2}Line: {1}{2}{2}", error.ErrorText,
error.Line, Environment.NewLine);
问题在于代码生成器似乎期望在某个地方有一个物理文件,当出现问题时,我们不会返回代码,而是返回无用的错误消息。我们强烈建议不要自动编译代码,尤其是当生成的代码有错误时(我们希望在故障排除时检查完整的、损坏的文件)。
我们还希望将输出作为字符串,我们可以随心所欲地获取和执行任何操作。
有没有办法让 T4 代码生成更像伪代码示例?我们正处于放弃 T4 工具的边缘,转而支持 CodeSmith 之类的工具,因为 T4 似乎过于有限/倾向于一种非常具体的管理模板和处理输出的方式。
【问题讨论】:
-
我在 CodeSmith 工作,我们确实支持内存模板。您还可以访问完整的 .net 运行时。如果您有任何问题,请联系我们。
-
如果您仍然想使用 T4 模板,我在我的 vs 扩展(T4 Awesome)中添加了一个功能,可以让您查看转换过程生成的代码文件。这应该可以帮助您调试并简单地理解转换过程。你可以下载它here。该功能在社区版中可用,因此您可以免费使用。
-
谢谢,伙计们。我确实最终选择了 CodeSmith,并且比 T4 更喜欢它。除了满足内存要求之外,最大的优势是设计器/智能感知支持更好,并且记录得更好(尽管不是彻底)而且他们有响应式支持来回答问题并帮助您前进。
标签: c# visual-studio-2013 code-generation t4 vsix