We have discussed in previous post we can create assembly at runtime and we can add code in that assembly at the same time we can access that assembly’s method or members with use of reflection.
.net provides Builder Class to build assembly and its members, module, property and many more.
AssemblyBuilder
ConstructorBuilder
EnumBuilder
EventBuilder
FieldBuilder
LocalBuilder
MethodBuilder
ModuleBuilder
ParameterBuilder
PropertyBuilder
TypeBuilder
To create assembly at runtime we should follow below steps.
àCreate an instance of AssemblyBuilder that defines assembly name and we are also passing another attribute AssemblyBuilderAccess which tell that we want to run this assembly and then save to disk. If we don’t use RunAndSave and use Save then it only Save to disk but we don’t allow to run.
AssemblyBuilder asb = AppDomain.CurrentDomain.DefineDynamicAssembly(
new AssemblyName("myAssembly"), AssemblyBuilderAccess.RunAndSave);
àCreate a ModuleBuilder in created assembly
ModuleBuilder mb = asb.DefineDynamicModule("myMod");
àCreate a TypeBuilder public class in Module we have created
TypeBuilder tb = mb.DefineType("myType", TypeAttributes.Class | TypeAttributes.Public);
àCreate a default constructor to create instance of our dynamically created type.
ConstructorBuilder cb = tb.DefineDefaultConstructor(MethodAttributes.Public);
àCreate a public, static method named Greeting that doesn't accept parameters or return a value, method can be any type as per our need. But it should be added in type we created.
MethodBuilder method = tb.DefineMethod("Greeting", MethodAttributes.Public | MethodAttributes.Static);
àCreate an ILGenerator for the method, which allows us to write code for it. we can write of code in dynamic method in IL code its very error prone when writing code here. Care should be taken to write ILCode
ILGenerator dynCode = method.GetILGenerator();
àAdd a line of code to the method, equivalent to Console.WriteLine, this code is in IL so we have to know IL to write dynamic assembly.
dynCode.EmitWriteLine("Hello, world!")
This is what we have created type at dynamically now if we want to use this dynamically code at runtime with use of reflection we can do as per our previous post.
àCreate an instance of the dynamic type
Type myDynType = tb.CreateType();
àCall the static method we dynamically generated
myDynType.GetMethod("Greeting").Invoke(null, null);
Apart from this we can access dll files or any of the assembly’s information and invoke method of it. Reflection can be very useful when we don’t know what will be come when code is going to execute.
No comments:
Post a Comment