Monday, 6 June 2011

Dynamically Loading Assemblies using the Path

Some of the time we need to take the reference of dlls at the run time. In that case we need to specify the path of dll at the run time and using that path application loads the assembly and uses the exposed methods at the run time.
Below mention code Calling Application uses the compiled dll of a class library from a given path. Hard coding of path can be avoided by using some configuration file entries or reading the data from the database.

1. Calling Application
public Form1()
{
InitializeComponent();
string path = @"C:/Documents and Settings/207692/Desktop/New Folder/HelloWorld.dll";
AppDomain d = AppDomain.CreateDomain("New Domain");
Assembly asmbly = Assembly.LoadFrom(path);
d.Load(asmbly.FullName);
//Object[] args = { 1, "2", 3.0 };
Object[] args = null;
Object[] args1 = { "Mr" };
// Walk through each type in the assembly looking for our class
foreach (Type type in asmbly.GetTypes())
{
if (type.IsClass == true)
{
if (type.FullName.EndsWith("." + "HelloClass"))
{
// create an instance of the object
object ClassObj = Activator.CreateInstance(type);
// Dynamically Invoke the method
object Result = type.InvokeMember("GetHello",
BindingFlags.Default | BindingFlags.InvokeMethod,
null,
ClassObj,
args);
Result = type.InvokeMember("GetHello",
BindingFlags.Default | BindingFlags.InvokeMethod,
null,
ClassObj,
args1);
}
}
}
}

2. Class Library

public interface IDemo
{
string GetHello();
string GetHello(string prefix);
}


namespace HelloWorld
{
public class HelloClass:IDemo
{
public string GetHello()
{
return "Hello Sandeep Shekhar";
}
public string GetHello(string prefix)
{
return ("Hello " + prefix + " Sandeep Shekhar");
}
}
}