Using the Roslyn compiler in your text templates

For long we have relied on EnvDTE in our text templates to gather metadata required create dynamically generated content for our solutions. While you can get a lot of information from EnvDTE, it is based on com, is extremely slow, and is not intuitive.

Recently I was watching a channel 9 video from Anders Hejlsberg https://channel9.msdn.com/Blogs/Seth-Juarez/Anders-Hejlsberg-on-Modern-Compiler-Construction. I was watching the video and then tough, why not try and use Roslyn inside our text templates, plus that was a great way to learn about it.

Getting started with using the compiler in your projects is very simple. In fact, all you need is to install the Microsoft.CodeAnalysis package from nuget and there you go. There are lots on information about the different libraries on the web, and you can find some getting started tutorial in the Roslyn github repo itself.

While it is very simple to get started in a standard project inside visual studio, it gets harder to use the class inside of a text template, as there are lots of dependencies to use all the features of Roslyn. So I have created a github repo where I added all you need to get started with using Roslyn in your text template. All you need to do is to clone all the ttinclude files in your project, include the NewsoftRoslyn.Core.ttinclude file in your text template, and you are good to go. Follow this link to get the include files: https://github.com/newsoftinc/Newsoft.Roslyn.T4

Class Description
NewsoftRoslyn.Core.ttinclude Main reference file. Include other text templates and provide a signle point
NewsoftRoslyn.Dependencies.ttinclude References all the required DLL to use Roslyn in your templates
NewsoftRoslyn.Helpers.ttinclude Provide some usefull helpers to work with Roslyn objects
NewsoftRoslyn.VsProject.ttinclude A wrapper of Microsoft.Analysis.Project
NewsoftRoslyn.VsSolution.ttinclude A wrapper of Microsoft.Analysis.Solution
Sample.tt A text template file with examples

 

The project on github include a sample.tt file that you can execute and see generated content inside sample.cs file.

 

 

Submit a Comment

Your email address will not be published. Required fields are marked *

Share This