There are some times where we need to load assemblies on the fly programmatically, even if there is no record of said assembly in the manifest and the act of loading external assemblies on demand is known as a dynamic load.
Using the Assembly class defined in the System.Reflection namespace we can dynamically load the assembly and discovers the methods, properties…etc on the fly. Assembly class provides the Load() method to load the assembly.
Here we load the some assembly dynamically and displays the it’s class methods. For that create EmployeeAssembly assembly by opening the visual studio => Create Project => Select Class Library and name it as EmployeeAssembly and add Employee class which two methods GetEmpId() and GetEmpName() as shown below.
public class Employee
{
public int GetEmpId()
{
return 101;
}
public string GetEmpName()
{
return "John";
}
}
Now build the project and you will get EmployeeAssembly.dll file in bin folder. Now create client application by selecting the Console Application from Visual studio and name it as LoadDynamicAssemblyExp and add below code.
using System;
using System.Reflection;
namespace LoadDynamicAssemblyExp
{
class Program
{
static void Main(string[] args)
{
try
{
string assemName = "EmployeeAssembly";
Assembly assm = null;
assm = Assembly.Load(assemName);
GBetTypesFromAssembly(assm);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}
}
static void GetTypesFromAssembly(Assembly asm)
{
Type[] types = asm.GetTypes();
foreach (Type t in types)
{
Console.WriteLine("Type: {0}\n", t);
GetMethods(t);
Console.WriteLine("\n\n");
}
Console.ReadLine();
}
static void GetMethods(Type t)
{
MethodInfo[] mi = t.GetMethods();
foreach (MethodInfo m in mi)
Console.WriteLine("Method Name: " + m.Name + " ; Return Type: " + m.ReturnType);
}
}
}
Here you are using System.Reflection namespace to load assembly dynamically. Add Reference for EmployeeAssembly assembly. Here GetTypesFromAssembly() method loads the types defined in the EmployeeAssembly and GetMethods() method displays all methods defined in each type. Even you can get properties, fields and interfaces implemented by using System.Reflection namespace.
The output of client application as shown below.