Examining the Assembly using Reflection in .NET
September 17, 2014 Leave a comment
The CLR code of a project is packaged into an assembly. We can inspect a range of metadata from an assembly that also the CLR uses to load and execute runnable code: classes, methods, interfaces, enumerations etc.
In order to inspect an Assembly in a .NET project we’ll first need to get a reference to the assembly in question. There are various ways to retrieve an assembly, including:
Assembly callingAssembly = Assembly.GetCallingAssembly(); Assembly entryAssembly = Assembly.GetEntryAssembly(); Assembly executingAssembly = Assembly.GetExecutingAssembly();
…where Assembly is located in the System.Reflection namespace.
The static methods above represent the following:
- GetCallingAssembly: to get the assembly one level up the call stack, i.e. which contains the method the current executing code
- GetEntryAssembly: to get the assembly which contains the entry point to the application, e.g. the Main method in a Console app
- GetExecutingAssembly: to get the assembly of the currently running code
There’s also a way to load a specific assembly using the GetAssembly(Type type) method. E.g. if you have a Customer class then you can load the assembly that contains the Customer class as follows:
Assembly specificAssembly = Assembly.GetAssembly(typeof(Customer));
Once you have the assembly you can read various metadata from it, examples:
Console.WriteLine("Full name: {0}", callingAssembly.FullName); Console.WriteLine("Location: {0}", callingAssembly.Location); Console.WriteLine("Loaded for reflection only? {0}", callingAssembly.ReflectionOnly); Console.WriteLine("Loaded from GAC? {0}", callingAssembly.GlobalAssemblyCache); Console.WriteLine(".NET Version: {0}", callingAssembly.ImageRuntimeVersion);
…which in my case outputs the following:
You may wonder what “loaded for reflection” means. You can get hold of an assembly in order to inspect its metadata without the possibility to execute any action on it. This is how we can load the assembly containing the “string” class in .NET:
Assembly reflectionOnlyAssembly = Assembly.ReflectionOnlyLoad("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
You can execute an assembly by creating an instance of it using the CreateInstance method. However, if the assembly was only loaded for reflection then CreateInstance will throw an exception. If you know that you only want to read some metadata from an assembly but not execute it then you can use the ReflectionOnlyLoad method to save time loading it fully into the AppDomain.
View all posts on Reflection here.