T4模板和运行时参数 [英] T4 template and run-time parameters

查看:76
本文介绍了T4模板和运行时参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在VS 2010中构建一个插件,但我陷于T4代.现在,我已经实现了(如MSDN所建议的)自定义T4主机以生成我的T4结果,并且我以这种方式使用它:

I am building a plug-in in VS 2010 and I get stuck at the T4 generation. Right now I have implemented (like MSDN suggests) a custom T4 host to generate my T4 results and I use it in this way:

        const string content = @"c:\Simple.tt";
        var engine = new Engine();
        var host = new MyTemplateHost();            
        var result = engine.ProcessTemplate(File.ReadAllText(content), host);
        foreach (CompilerError error in host.Errors)
        {
            Console.WriteLine(error.ErrorText);
        }

这有效,直到我在模板中传递参数为止.一旦我在.tt文件中创建了一个参数,主机就会吓一跳,说它不知道如何解决它.我看到您可以使用TemplateSession来做到这一点,但我不知道如何将其传递给我的主机?是否有更好的方法使用C#从.tt生成代码并在运行时传递参数?也许我走错了路.

This works until I pass a parameter in the Template. As soon as I create a parameter in the .tt file, the Host freak out saying that it doesn't know how to resolve it. I saw that you can use the TemplateSession to do that but I didn't figure out how to pass it to my Host? Is there a better way of generating code from a .tt using C# and passing parameters at run-time? Maybe I am on the wrong path.

推荐答案

在Visual Studio 2010中,对T4模板引擎进行了彻底的更改.现在,您可以直接运行模板文件,然后将其任何参数类型传递给它.

Within Visual Studio 2010 the T4 template engine has been radically changed. Now you can run directly a template file and pass to it any parameter type you want.

        var template = Activator.CreateInstance<SimpleTemplate>();
        var session = new TextTemplatingSession();
        session["namespacename"] = "MyNamespace";
        session["classname"] = "MyClass";
        var properties = new List<CustomProperty>
        {
           new CustomProperty{ Name = "FirstProperty", ValueType = typeof(Int32) }
        };
        session["properties"] = properties;
        template.Session = session;
        template.Initialize();

此语句将处理以下模板:

This statement will process the following template:

<#@ template language="C#" debug="true"  #>
<#@ output extension=".cs" #>
<#@ assembly name="System.dll" #>
<#@ import namespace="System" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="SampleDomain.Entities" #>
<#@ parameter name="namespacename" type="System.String" #>
<#@ parameter name="classname" type="System.String" #>
<#@ parameter name="properties" type="System.Collections.Generic.List<CustomProperty>" #>

using System;
using System.Collections.Generic;
using SampleDomain.Entities;

namespace <#= this.namespacename #>
{
public class <#= this.classname #>

老实说,不再需要主机了……

So honestly the host is not really needed anymore ...

这篇关于T4模板和运行时参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆