Hi all, This is the second example. It's adapted from the thread "Adding a Field to an existing assembly" posted on http://groups.google.pt/group/mono-cecil/browse_thread/thread/4cc8c1ff77b400f/2c2b86c9ef848714?hl=pt-PT&lnk=gst by Jair Cazarin on May 28 2009 (Jb Evain was part of the thread too).
While the referred thread discusses importing a field from one assembly into another , the FieldInjection method injects a freshly created field into an assembly. The return type of the field can be whatever you like. Attributes are not handled. As stated in the previous post (Property injection example http://groups.google.pt/group/mono-cecil/browse_thread/thread/f2a3df3a34e68639), the load and save symbols part isn't working quite as it should (the second time I do it, it reports some error) so I commented it. using System; using Mono.Cecil; namespace CustomFieldsInjection { public partial class Injector { public static void FieldInjection(string assemblyFilename, string typeName, string fieldName, Type returnType, FieldAttributes attrs) { //Get the Assembly AssemblyDefinition assembly = AssemblyFactory.GetAssembly (assemblyFilename); //Load the debugger symbols file // assembly.MainModule.LoadSymbols(); //Get all the types in the given typeName (the type we are going to add the property to) TypeDefinition assemblyTypes = assembly.MainModule.Types [typeName]; //Get a TypeReference for the return Type TypeReference fieldType = assembly.MainModule.Import (returnType); //Define field signature FieldDefinition fieldDefinition = new FieldDefinition( fieldName, fieldType, attrs); //Add the new field definition to the field collection of the assembly assemblyTypes.Fields.Add(fieldDefinition); //Save the debugger symbols file // assembly.MainModule.SaveSymbols(); //Save the patched assembly back to disk AssemblyFactory.SaveAssembly(assembly, assemblyFilename); } } } Enjoy. Tiago Freitas Leal --~--~---------~--~----~------------~-------~--~----~ -- mono-cecil -~----------~----~----~----~------~----~------~--~---
