Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Customize T4 Scaffolding With PowerShell

I want to create a Custom Scaffolder that uses arbitrary PowerShell logic. It can render T4 templates (multiple ones if I want), with the result being output:

  • As a new file in your project
  • as a new code block inserted into an existing class
  • my PowerShell logic can use Visual Studio’s “code model” API to manipulate files and code elements in other arbitrary ways.

How to Customize T4 Scaffolding With PowerShell?

like image 322
Samy Avatar asked Nov 19 '12 12:11

Samy


1 Answers

From http://blog.stevensanderson.com/2011/04/07/mvcscaffolding-creating-custom-scaffolders/:

In Package Manager Console of Visual Studio execute the following command :

Scaffold CustomScaffolder ClassName

This adds a CodeTemplates folder to your project, containing files for the new scaffolder.

As you can see, we’ve got two files:

  • A PowerShell script (.ps1), where we can put arbitrary logic to decide what templates get rendered and where the output goes. By default, it renders a T4 template and uses the output to create a new file called ExampleOutput in the root of your project.
  • A T4 template (.t4), i.e., the thing that the default .ps1 file renders. By default this generates a simple C#/VB class (depending on your project type). If you want to see this working, you can run the custom scaffolder right away:

    Scaffold ClassName

This will generate a new class file, ExampleOutput.cs, in the root folder of your project. That’s really just to show you how it works. We don’t really want that, so don’t run the new scaffolder yet, or if you already have done, delete ExampleOutput.cs

like image 139
Mohsen Alikhani Avatar answered Oct 24 '22 11:10

Mohsen Alikhani