Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving a DynamicMethod to disk

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?

like image 644
Mike Caron Avatar asked Jun 14 '11 19:06

Mike Caron


2 Answers

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");
like image 141
rqmedes Avatar answered Sep 30 '22 19:09

rqmedes


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.

like image 32
svick Avatar answered Sep 30 '22 18:09

svick