7

I have inherited code that uses DynamicMethod to generate methods at runtime. I also need to modify some of the code that is being generated.

Since I am a n00b at MSIL, I would love to be able to load the generated code up in Reflector and ensure that the code does what I pray that it does ;)

Only, I can't figure out how to serialize the "Anonymously Hosted DynamicMethods Assembly" to disk. Is this possible? If so, how?

svick
  • 236,525
  • 50
  • 385
  • 514
Mike Caron
  • 14,351
  • 4
  • 49
  • 77

2 Answers2

9

Try this,

  var assemblyName = new AssemblyName("SomeName");
  var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave, @"c:");
  var moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName.Name, assemblyName.Name +  ".dll");

  TypeBuilder builder = moduleBuilder.DefineType("Test", TypeAttributes.Public);
  var methodBuilder = builder.DefineMethod("DynamicCreate", MethodAttributes.Public, typeof(T), new[] { typeof(IDataRecord) }); 
  /* this line is a replacement for your  new DynamicMethod(....)  line of code

  /* GENERATE YOUR IL CODE HERE */

  var t = builder.CreateType();
  assemblyBuilder.Save(assemblyName.Name + ".dll");
rqmedes
  • 540
  • 2
  • 14
3

I think that if you want to load the method in Reflector or dotPeek, you need to create an actual assembly. To do this, use MethodBuilder instead of DynamicMethod. Most of the usage of them should be the same.

svick
  • 236,525
  • 50
  • 385
  • 514
  • Sorry to keep this open for so long. I wanted to wait until I could implement this before I accepted, but of course I'm working on another project now! Still, this seems like the only real answer, so when I get back to working on this, I'll know what to do. – Mike Caron Jun 16 '11 at 13:19