Hello guys. I have some problems with injecting new class with one method inside it. Basicly this class is placed in my project and i need to insert it in assembly using dnlib, then call the method from it from constructor.
My code sample:
AssemblyDef assembly = AssemblyDef.Load(FilePath); ModuleDef module = assembly.Modules[0]; Importer importer = new Importer(module); // Create new importer. IMethod meth = importer.Import(typeof(MyClass).GetMethod("Initialize")); // Trying to import initialization method and then place it into a new class. TypeDef type = new TypeDefUser("NewClass"); // Creating new type. type.Attributes = TypeAttributes.Class; // Setting class attribute. type.Methods.Add(meth.ResolveMethodDef()); // Catching Null exception here. module.Types.Add(type); // Adding new type into our module. //////////////////////////////////// MethodDef cctor = module.GlobalType.FindOrCreateStaticConstructor(); cctor.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Call, meth)); // Need to call that method here.
So, i also have another question opposite topic subject. How can i enumerate all assembly references with dnlib?