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:
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With