DEV Community

Dominic Pascasio
Dominic Pascasio

Posted on • Edited on

2

.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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay