Code Generation: T4Scaffolding with Custom C# Assembly
I’ve been working on using the T4Scaffolding to generate code in a project. One of the things I want to accomplish is to keep the main code logic in a C# assembly and use the powershell couped with the T4 templating to just handle the code gen vs. the logic.
The first step required is to get the T4Scaffolding nuget package. Next, we want to create our own custom scaffolder. To learn more about creating a custom scaffolder, as well as to learn how MvcScaffolding is built on top of T4Scaffolding, you can read Steve Sanderson’s blog post series.
I will attach my code example, first let’s go through the series of steps here.
1. Create a C# solution with two class library projects, I used default ‘ClassLibrary’ and ‘Test’ to prototype and test out the concept.
2. In the powershell console, install the T4Scaffolding nuget package:
(make sure you have ‘classlibrary’ selected in the ‘default project’, ie
3. Create your custom scaffolder:
You should see the folder structure inside your project created, it will generate a simple example for you:
4. Next step is to create some code in our Test project that we can use in our template. My example is simple – but shows a object graph common perhaps in your solution:
(see attached code sample)
5. Now that we have this code in place – time to get into our Generator ps1 code – please note, I’m a powershell newbie, so if there is a better way, ping me
I need to load the assembly, there are several ways to accomplish this:
(the # is commented out powershell). It is required that we load the assembly so that ps can reflect over the types and be able to execute the c# code.
Now we want to execute our generator, my assembly is ‘Test’ with namespace ‘Test’ – with a Generator class that has a static ‘Get’ call:
Now that we have our ‘Entity’ object – we can pass this entity to our t4 template to create our class:
I am adding a new property to the ‘Model’ called ‘Entity’ that contains our Entity from our Get() call.
Now take a look at the T4 template- I need to include the assembly and namespace’s that will be used:
Lastly, we can get to the property collection, looping through it to create a class member (or any other logic needed).
Note: there is a add-classmember cmdlet in T4 Scaffolding, but for now I had to resort to this because the performance of it at the time of this writing was horrific.
But regardless, this type of logic could be used for other things – ie. building up a fluent validator in a constructor, etc…
After building the code, we can run our custom scaffolder:
Hope this helps anyone else working through this. The key was to get the correct assembly loaded code in the ps1 file and the correct ‘assembly’ and ‘import’ statements in my T4 template.