Wednesday, 7 August 2013
Generate Repositories and Controllers using T4 Template
In my previous post I shared a modified template generated by Entity Framework 5 to create entity classes. In this post I am sharing a few more templates. Actually I decided to design a few reusable templates that will create a complete repository implementation with UnitOfWork design pattern. There is also another template “ControllerGenerator” that creates necessary Web API controller classes. The template creats all the classes, but for those repositories to work along with the controllers we need to add necessary depenecy injection library to inject into controller. This post is only about the T4 template related information.
The updated templates are available under the project “CodeGenerator”in the below location.
Along with the templates I want to share some information that really helps designing or developing T4 templates specially if you are new to it. A few things that I was needed while creating the templates are:
1. I was looking for a way to generate multiple files from the single template. In general a template generates a single file.
2. Putting common logic in a helper template.
There are very good editors & tools provided by “Tangible”. These tools provide several use full templates on top of which we can build our required templates. It also provides design tools. We can download them from below link
The Tangible editor helped me two achieve both the requirements and more significantly the first one. With the help of this editor I can generate multiple classes easily. This very much required. For example, if we want to generate repositories or Web API controllers.
We can put common logic in a helper template. We can create an include template with extension “.ttinclude” and refer that in our actual templates. We can put all helper classes there which will keep template clean and specific.
While creating the templates one issue that I faced is adding reference to projects. This can be done by using two libraries: EnvDTE and VSLangProj. But I started facing problem when I put my projects inside SolutionFolder. But after goggling for a while I found the solution. We need to refer another assembly “EnvDTE80”. In case we have solution folders, the Projects collection return by the EnvDTE ‘s Solution object are basically “SolutionFolders”. We can then get the ProjectItem of a SolutionFolder which will have SubProjects. These subprojects are the Projects inside the solution folder. Actually while looping through the Solution.Projects collection we can verify if the Project is a solution folder by checking “Kind” property of the Project with “ProjectKinds”.
Please feel free to add your comments and feedback if any.