You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用.cs.t4模板生成代码?接手项目遇模板运行困惑

How to Run This Parameterized T4 Template (Controller.cs.t4)

Hey there! Let me break down how to run this parameterized T4 template you found. Unlike the auto-generating T4 templates you've seen in tutorials, this one is designed to take custom parameters (like ControllerName, Namespace) before it can generate a valid .cs file—here's exactly what you can do:

Why It Doesn't Auto-Generate

First, notice the <#@ parameter #> directives at the top of your template. These mean the template requires external input values to work—without them, it can't produce a complete, valid controller class. That's why it doesn't auto-generate like simpler T4 templates.

Method 1: Use a "Driver" T4 Template (Easiest in Visual Studio)

Create a new T4 template file (e.g., GenerateController.tt) in the same directory as Controller.cs.t4, then add this code to it:

<#@ template language="C#" #>
<#@ include file="Controller.cs.t4" #>
<#
    // Fill in your desired parameter values here
    ControllerName = "HomeController";
    ControllerRootName = "Home";
    Namespace = "YourProjectNamespace.Controllers";
    AreaName = ""; // Leave empty if no area, or set to something like "Admin"
    
    // Trigger the template generation
    this.Generate();
#>

Once you save this driver template, Visual Studio will automatically process it and generate a .cs file (e.g., GenerateController.cs) with your fully populated controller class. You can tweak the parameter values anytime and re-save to regenerate.

Method 2: Call the Template via C# Code (For Custom Automation)

If you want more control (like integrating this into a build script or tool), you can use the Templating Engine API to run the template programmatically. Here's a simplified example:

using Microsoft.VisualStudio.TextTemplating;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        // Initialize the T4 engine
        var engine = new Engine();
        string templatePath = @"Path\To\Your\Controller.cs.t4";
        string templateContent = File.ReadAllText(templatePath);

        // Set up your parameter values
        var session = new TextTemplatingSession();
        session["ControllerName"] = "ProductController";
        session["ControllerRootName"] = "Product";
        session["Namespace"] = "YourProject.Controllers";
        session["AreaName"] = "Catalog";

        // Create a simple host to handle parameter resolution
        var host = new CustomTemplateHost { Session = session };

        // Process the template and get the output
        string generatedCode = engine.ProcessTemplate(templateContent, host);

        // Save the generated controller to a file
        File.WriteAllText(@"Path\To\Output\ProductController.cs", generatedCode);
    }
}

// Minimal implementation of the ITextTemplatingEngineHost interface
public class CustomTemplateHost : ITextTemplatingEngineHost
{
    public TextTemplatingSession Session { get; set; }

    public object GetHostOption(string optionName) => null;
    public bool LoadIncludeText(string requestFileName, out string content, out string location)
    {
        content = string.Empty;
        location = string.Empty;
        return false;
    }
    public void LogErrors(CompilerErrorCollection errors) { }
    public AppDomain ProvideTemplatingAppDomain(string content) => AppDomain.CurrentDomain;
    public string ResolveAssemblyReference(string assemblyReference) => assemblyReference;
    public Type ResolveDirectiveProcessor(string processorName) => null;
    public string ResolvePath(string path) => path;
    public string ResolveParameterValue(string directiveId, string processorName, string parameterName)
    {
        return Session[parameterName]?.ToString();
    }
    public void SetFileExtension(string extension) { }
    public void SetOutputEncoding(System.Text.Encoding encoding, bool fromOutputDirective) { }
}

Notes

  • Make sure you have the Text Template Transformation component installed in Visual Studio (you can add it via the Visual Studio Installer if missing).
  • When using the driver template, ensure the include path points correctly to Controller.cs.t4 if they're in different directories.
  • Adjust the parameter values (ControllerName, Namespace, etc.) to match your project's structure.

内容的提问来源于stack exchange,提问作者Josy Sclei

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 16:59:05