DEV Community

Dominic Pascasio
Dominic Pascasio

Posted on • Updated on

.NET - Create a Simple Scaffolding Tool

We will use Text Template Transformation Toolkit also known as T4.

  1. Create a console application.

    dotnet new console -o MyTool
    
  2. Create a template file ClassTemplate.tt in the project directory.

    <#@ output extension=".cs" #>
    <#@ template language="C#" hostspecific="true" #>
    <#@parameter type="System.String" name="ClassName" #>
    public class <#=ClassName#>
    {  }
    
  3. To process the template, we need a templating engine, Mono.TextTemplating is an open source implementation for that.

    dotnet add package Mono.TextTemplating
    
  4. In Program.cs, write the code for processing the template.

    var className = args[0];
    var templatePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ClassTemplate.tt");
    var outputPath = Path.Combine(Directory.GetCurrentDirectory(), className); 
    var generator = new Mono.TextTemplating.TemplateGenerator();
    
    var session = generator.GetOrCreateSession();
    session.Add("ClassName", className);
    
    generator.ProcessTemplate(templatePath, outputPath); 
    
  5. Go to the desired directory and run:

    ProjectA> dotnet run path/to/MyTool Person
    

    This creates Person.cs in ProjectA directory:

    public class Person
    {  }
    

If you want to install and run it as a dotnet tool, read this.

Resource

Microsoft Docs

Top comments (0)