Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looking for a way to manipulate .Net CIL at runtime

In Java we have used the javaagent argument and ASM (http://asm.ow2.org/) utilities to modify the byte code at run/load time in memory by the classloader . (aka Add a method call to a method in a class dynamically).

Once example of this is where you remove all calls to Log4j to speed up an application (http://surguy.net/articles/removing-log-messages.xml).

I’m trying to figure out how to do this same process on runtime with C# / .Net. I have seen that you can manipulate the CIL for .Net, but I haven’t found an example of this at runtime.

System.Reflection.Emit seems to be the closest .Net equitant where you can dynamically create classes, but is there a way to add to or override existing classes using this?

like image 688
James Avatar asked Apr 28 '11 17:04

James


2 Answers

I have never used Mono.Cecil for generating dynamic code (it does make your life much easy if you want to instrument assemblies though).

In .Net if you want to generate code you can use System.CodeDom and System.Reflection.Emit. One particular useful class that enables you to inject methods dynamically is DynamicMethod.

like image 176
Vagaus Avatar answered Nov 01 '22 17:11

Vagaus


Check out the newer features in .net 4, I think most of what your looking for is in the System.Dynamic namespace.

Check out this post on DuckTyping

like image 1
RandomNickName42 Avatar answered Nov 01 '22 19:11

RandomNickName42