Monday, February 24, 2014

Load Assembly to dynamically create an instance of a class


This will load an assembly and dynamically create an instance of a class.


...
string asmLocation = Path.Combine(AssemblyDirectory(), "TheDLL.dll");
Assembly asm = Assembly.LoadFile(asmLocation);
var theType = asm.GetType("TheType", true, false);
IRunnable runnable = Activator.CreateInstance(theType) as IRunnable;

runnable.Execute();
...

 
private string AssemblyDirectory()
{    string codeBase = Assembly.GetExecutingAssembly().CodeBase;
    UriBuilder uri = new UriBuilder(codeBase);
    string path = Uri.UnescapeDataString(uri.Path);
           
    return Path.GetDirectoryName(path);
}

No comments: