December 06, 2013

Embedded Code Generator Using T4

Have you ever been working or architecting on N-tier framework? If you have, you know this fact that creating a lot of classes inside the different layers (like Data, Business, Service or UI Layer) is troublesome for developers. And, that is why you might had been working on a Code Generator for your framework to produce base classes of layers, in order to reduce developer’s job. Regularly, Code Generators were being implemented as a desktop application that were totally separated from the main application. I always was thinking about this issue that it would be better if I could generate required classes on demand inside the main application. Luckily, after learning T4, finally I could implement this kind of embedded code generator. In my ASP.NET MVC framework I am using Entity Framework as an ORM and 3-tier application.
  • In DataLayer I have an Entity-Framework model.
  • In the UI Layer I need to generate all the Base Controllers.
  • In the Service layer I need to generate all the Base Services as well.
Following you can read my approach for generating all the Base Classes using T4.

1- I have created the fully executable body of a Base Class inside the TEXT file, and replace the name of specific class with a reserved sign.

for example the ultimate person class needs to have a constructor like this:
public IPersonService personService;
public PersonBaseService(PersonService  _PersonService)
   this.personService = _PersonService;

I replaced Person with this sign: “#entity#” inside the TEXT file. The T4 will replace this sign with proper existing class name from entity-framework.
public I#entity#Service #entity#Service;
public #entity#BaseController(I#entity#Service _#entity#Service)
this.#entity#Service = _#entity#Service;

2- I have created a T4 inside the Service Layer that is loading this TEXT file. Trying to loop on Entity Framework and for each classes that represent a table from database, replace “#entity#” sign and generate a new class. With this solution after having any changes on database and refreshing the Entity-Framework, I just need to run T4 template. consequently all the needed Service Classes of all tables are going to be generated really fast. using this method easily we can create embedded and totally dynamic code generator inside an application.