.NET: Unable to cast object to interface it implements

I hat the same problems with a library of mine providing “plugin”-functionality… I got it finally working…

Here was my problem: I had one main assembly using plugins, one assembly with the plugin (Plugin.dll) AND (important) another assembly providing the plugin-functionality (Library.dll).

The Plugin.dll referenced the main assembly (in order to be able to extend it) and the Library.dll with the plugin-func. – it’s binaries got to a directory “./Plugins” relative to the main assembly.

The main assembly also referenced the plugin-func. assembly in order to use the “PluginManager” is wrote. This “PluginManager” gets a path and loads all *.dll files via reflection in order to analyze if there is a “IPlugin”-interface (which comes from Library.dll too).

Everytime I called the PluginManager to load the plugins it could not cast them to “IPlugin” although they implemented it.

I nearly got mad – but then I found out the whole problem. By compiling the plugin there was not only the “Plugin.dll” but the “Library.dll” written to the “./Plugins” directory. By accidentally loading the “Library.dll” every time with my PluginManager I now had two types of “IPlugin” – one in the actual “Library.dll” that is used from the main assembly and one that was loaded through my PluginManager – and those were incompatible!

Attention – if you just do not load “./Plugins/Library.dll” you nevertheless encounter the problem – because if you load “Plugin.dll” which references “Library.dll” then it just uses the one in the same directory… TILT…!! My PluginManager now just deletes “Library.dll” where it find it.

The clue is: Be sure that you do not access two assemblies in different contexts!

Leave a Comment