Dynamic DLL loading

I am trying to just load a DLL written in C # at runtime and create an instance of the class in this 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 occur, and if I go through the code, I can go through the FileReleaseHandler class as it executes the constructor, but the handler value is always null.

What am I missing here? or is there even a better way I should do this?

+6
c #
source share
5 answers

Where is TestInterface.INeedHelp indicated? One common problem is that you have the same interface in multiple assemblies. If both the calling and dynamically loaded assemblies refer to the same interface in the same assembly, everything should be in order.

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

+4
source share

Try setting the result of Activator.CreateInstance to the object directly, rather than casting.

Perhaps FileReleaseHandler does not implement TestInterface.INeeedHelp , in which case it will be set to null through "like TestInterface.INeeedHelp".

+4
source share

Check assemblies uploaded to the application domain. Are there two assemblies with the TestInterface.INeedHelp interface? My suspicion is that LoadFrom associates this created object with a different TestInterface.INeedHelp than the one you are trying to execute. Try to make a regular lowered, and not the so-called "safe" throw and see what error you get.

+1
source share

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

To verify that this is the case, try assigning a result to the object.

0
source share

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) 
0
source share

All Articles