Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically Loading a DLL

Tags:

c#

I am trying to simply load a dll written in C# at run time and create an instance of a class in that dll.

Assembly a = Assembly.LoadFrom(@"C:\Development\DaDll.dll");
Type type = a.GetType("FileReleaseHandler", true);
TestInterface.INeeedHelp handler = Activator.CreateInstance(type) as    TestInterface.INeeedHelp;

No errors are thrown, and if I step through the code I can walk though the FileReleaseHandler Class as it executes the constructor but the value of handler is always null.

What am I missing here? or even is there a better way I should be going about this?

like image 343
etoisarobot Avatar asked Apr 16 '10 14:04

etoisarobot


2 Answers

Where is TestInterface.INeedHelp defined? One common problem is if you've got the same interface in multiple assemblies. If both the caller and the dynamically loaded assembly reference the same interface in the same assembly, it should be okay.

One subtlety is that if the assembly is in a different directory to the calling assembly, it may end up loading a different copy of the same assembly, which can be very irritating :(

like image 194
Jon Skeet Avatar answered Sep 28 '22 06:09

Jon Skeet


Try setting the result of Activator.CreateInstance to an object directly, and not casting.

It's possible FileReleaseHandler does not implement TestInterface.INeeedHelp, in which case, this will be set to null via the "as TestInterface.INeeedHelp".

like image 22
Reed Copsey Avatar answered Sep 28 '22 07:09

Reed Copsey