c# - 将对象传递给 T4 模板

标签 c# .net templates t4

我有一个类型为 User 类的对象 u1。用户具有属性 name。如何将 u1 传递给 T4 模板?我正在尝试做一些非常简单的事情:

User u1 = new User("John"); 


模板脚本:

Hello <# u1.Name #>

最佳答案

我们做了类似的事情。我们的解决方案包含以下要素:

  • 自定义主机
  • 自定义模板基类(“继承”模板指令的属性)
  • 主机特定模板(模板指令的“hostspecific”属性)

自定义主机由模板本身想要对其调用方法的对象聚合。

interface ICallbackInterface
{
    void CallbackFxn();
}

[Serializable]
public class MyCustomHost : ITextTemplatingEngineHost, ITextTemplatingSessionHost, IStencilFileRecordManagement
{

    private ICallbackInterface callback = null;
    public MyCustomHost(ICallbackInterface cb)
    {
        callback = cb;
    }

    public void CallbackFxn()
    {
        callback.CallbackFxn();
    }
}

public abstract class MyTemplateBase : TextTransformation
{
    public virtual MyCustomHost CustomHost
    {
        get
        {
            dynamic metame = this;
            MyCustomHost rval = null;
            try
            {
                /// <summary>
                /// The "Host" property will be added to the generated class by the T4 environment whenever a 
                /// "hostspecific" template is processed. 
                /// </summary>
                rval = metame.Host as MyCustomHost;
            }
            catch (RuntimeBinderException e)
            {
                logger.ErrorException(
                    "Received the following exception while processing a stencil template", e);

            }
            return rval;
        }
    }
}

现在,在我们的任何模板中,我们都可以使用自定义主机属性调用实际开始处理的对象的方法,例如:

<# CustomHost.CallbackFxn(); #>

此外,我们不在 VS 中使用 T4 或使用单独的可执行文件——我们链接 Microsoft.VisualStudio.TextTemplating.10.0 和 Microsoft.VisualStudio.TextTemplating.Interfaces.10.0 程序集。

编辑

我们使用 T4 模板允许用户定义他们自己的插件,以便在我们产品工作流程的特定步骤中使用。所以用户模板被上传到我们的系统,并像这样处理:

using Microsoft.VisualStudio.TextTemplating;

class UserPluginWorkflowComponent : ICallbackInterface
{
    public void CallbackFxn()
    {
        // invoked by user plugin
    }

    public void ExecuteUserPlugin()
    {
        MyCustomHost host = new MyCustomHost(this);
        host.TemplateFileValue = "UserPluginTemplateFilename";
        Engine engine = new Engine();
        string pluginResult = engine.ProcessTemplate(
            userPluginTemplateFileContents, 
            host);            
        if (!host.Errors.HasErrors)
        {
            // use pluginResult in some meaningful way
        }
    }
}

关于c# - 将对象传递给 T4 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6192084/

相关文章:

C# 画线 OnPaint() 与 CreateGraphics()

c# - GraphicsPath.Flatten() 对绘图性能有何影响?

c++ - 从其他容器中辨别 smart_pointer 的模板函数

c++ - 基类模板的成员在具有相同模板参数的派生类模板中超出范围

c++ - 模板类中的c++运算符重载Im正在尝试构建重载<<以打印树

c# - MVC 日期时间模型绑定(bind)

c# - 线程,流畅的 nhibernate 和保存数据陷入僵局

c# - 什么都不抛出时的异常效率

c# - Microsoft 图表控件/Dundas 图表清除内容?

c# - .Net C# 如何连接到外部 SQL Server 数据库? OleDb 还是其他?