简体   繁体   中英

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM