etoisarobot
etoisarobot

Reputation: 7814

Dynamically Loading a DLL

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?

Upvotes: 6

Views: 929

Answers (5)

Jipy
Jipy

Reputation: 115

I would do something like :

Assembly a = Assembly.LoadFrom(@"C:\Development\DaDll.dll");  
object obj = a.CreateInstance("fullClassName",other params) as IMyType
//(if it implements an interface you referenced)

Upvotes: 0

mfeingold
mfeingold

Reputation: 7134

The problem is that the LoadFrom method loads the dll into "LoadFrom" context which is different from the default context. The rules of type resolution for the types in this context differ from the ones you are used to. It is possible that the INeedHelp interface as defined in your main module from the standpoint of the runtime is different from the interface with the same name as coming from the LoadFrom context. This will cause the cast (as TestINterface) return null.

To see if this is the case try to assign the result to an object.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1503090

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 :(

Upvotes: 4

MaxGuernseyIII
MaxGuernseyIII

Reputation:

Check the assemblies that are loaded into the application domain. Are there two assemblies with the TestInterface.INeedHelp interface in it? My suspicion is that the LoadFrom is binding this created object to a different TestInterface.INeedHelp than the one to which you are trying to cast. Try doing a normal downcast rather than a so-called "safe" cast and see what error you get.

Upvotes: 1

Reed Copsey
Reed Copsey

Reputation: 564771

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".

Upvotes: 4

Related Questions