Posts filed under ‘Reflection’

Creating Assembly at runtime with Reflection (Reflection Part-2)

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.

April 27, 2010 at 4:25 am Leave a comment

Reflection in .net (Reflection Part-1)

As a .net developer or any time worked with .net we are familiar with word Reflection. We rarely use reflection in our development but it is very powerful feature provided by .net framework.

It gives information of types, methods, properties, code etc at runtime dynamically generated assembly. With use of reflection we can access assembly written in .net or any other platform or even we can generate or create assembly at runtime as per our need.

To use reflection we need to import or add System.Reflection and or System.Reflection.Emit namespace in our application.

Let’s take a look how to use reflection to create type instance at run time.

We want to show string length in console and for that we don’t want to use Length property.

To use any type at dynamically we should follow below steps.

àCreate instance of type

Type t = typeof(StringBuilder);

àCreate constructor of type

ConstructorInfo ci = t.GetConstructor(new Type[] { typeof(string) });

àInvoke constructor

Object sb = ci.Invoke(new Object[] { “Hello, world!” });

àCreate a PropertyInfo instance representing the StringBuilder.Length property.

PropertyInfo lengthProperty = t.GetProperty(“Length”);

àRetrieve the Length property and cast it to the native type.

int len = (int)lengthProperty.GetValue(sb, null);

Console.WriteLine(len.ToString());

We can use any type as per above example it’s not necessary that it must be provided by .net framework. we can even create instance of type created by ourselves dll files.

If we check assembly’s information in project property we can see assembly’s name, assembly’s version, assembly’s copy write information, assembly’s version and many things that gives information for an assembly we can access all these information with use of Reflection.

First we need to load assembly in our current application domain.

That can be done by methods provided by Assembly class all are static methods.

Assembly.Load :Loads an assembly by name, usually from the Global Assembly

Cache (GAC)

Assembly.LoadFile :Loads an assembly by specifying the filename

Assembly.LoadFrom :Loads an assembly given its filename or path

Following methods allows to load assembly but only for examine we don’t run code of that assembly. That is also code reflection-only context.

Assembly.ReflectionOnlyLoad :Loads an assembly in reflection-only context, usually from the GAC

Assembly.ReflectionOnlyLoadFrom :Loads an assembly in reflection-only context, by specifying the filename

We can access assembly’s information by its attribute first need to iterate through attributes of it.

Like below are some of the assembly’s attribute.

AssemblyCopyrightAttribute

AssemblyCompanyAttribute

AssemblyDescriptionAttribute

To access all members like property, methods ,fields members we can call GetMembers. In that we can pass different BindingFlags enumerator.

Depends of BindingFlags we get array of members in a given assembly. We can also pass more than one BindingFlags enumerator.

Type t = typeof(String);

MemberInfo[] mi = t.GetMembers(BindingFlags.NonPublic | BindingFlags.Static);

Above code will return all the private and static members of String type. There are also other options in BindingFlags enumerator depends on it we get list of members.

In next part we will discuss about how to create assembly at runtime.

April 26, 2010 at 3:39 am Leave a comment


Archives

Categories

 

May 2012
M T W T F S S
« Feb    
 123456
78910111213
14151617181920
21222324252627
28293031  

Blog Stats

  • 1,999

Follow

Get every new post delivered to your Inbox.