Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# How to generate code from code

Is it possible to generate and build some c# code based on the code from the same project. I tried with T4 and Reflection, but there are some assembly locking issues. Is there any other way?

like image 476
Marko Avatar asked May 02 '10 17:05

Marko


2 Answers

Reflection works fine for me. You can get around assembly locking issues by isolating your build task to a separate AppDomain within VS. When the task completes, any assemblies you need to use for code generation will be unloaded together with the task's AppDomain. See AppDomainIsolatedTask.

like image 100
Anton Tykhyy Avatar answered Sep 29 '22 19:09

Anton Tykhyy


You can definitely write your own code generator, all in C# - after all, "code" that's being generated is just a text file you write out.

But what's wrong with T4 templates? They offer a lot of functionality that you don't have to reinvent yet again - why not use it? Can you tell us in more detail what problems you're having with T4?

T4 is really just a bunch of classes in .NET, too - so you could definitely write your own code generator handling some of the logic, and use T4 to do the templating & replacing those template values part. But again: in order to help you diagnose your T4 problems, we'd need to know more about those....

like image 38
marc_s Avatar answered Sep 29 '22 17:09

marc_s