Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compiling dynamic code at runtime using T4 and C#

The articles I have read on T4 using TextTemplatingFilePreprocessor show how to dynamically generate code that becomes part of a project, and is compiled with the project.

Is it possible to use T4 to generate code that is compiled at runtime, outputted to a dll, and loaded and executed, with said code having access the usual visibility capabilities associated with a dll?

If so, could you please point me to an example.

I'm effectively trying to do the same thing as generating a dynamic dll using IL, but rather using C#.

EDIT

The specific case I need this for is straightforward. I am writing a message router that routes messages to services. Services may be local or remote. A declarative script is compiled into C#. The dynamic part is "is this service local or remote?". The output C# is changed accordingly. The style of routing is different for local / remote, hence the dynamic nature.

This is one example of what I need.

like image 906
IamIC Avatar asked Mar 01 '13 17:03

IamIC


1 Answers

To do this, you need to know two things:

  1. You can use run-time T4 template to generate some text at runtime, including C# source code.
  2. You can use CSharpCodeProvider to compile an assembly from text at runtime. Or you could manually run csc.exe (the command-line C# compiler) on the generated text, but that would more complicated. (Actually CSharpCodeProvider does exactly that behind the scenes.)

The code could look like this:

var template = new RuntimeTextTemplate();
string code = template.TransformText();

var compiler = new CSharpCodeProvider();
var result = compiler.CompileAssemblyFromSource(
    new CompilerParameters { OutputAssembly = "assembly.dll" }, code);
like image 117
svick Avatar answered Sep 25 '22 18:09

svick