Read this if you're getting an InvalidCastException when referencing a type created with AppDomain.CreateInstanceFrom
I was helping someone out with an issue the other day. Basically we were attempting to create an instance of an object within an AppDomain and then use that object. Unfortunately when casting the object from the object returned from CreateInstance to the desired type we were getting an InvalidCastException. Looking at the debugger showed that both types were identical (base folder, version, key, etc.).
The code looks something like this:
object obj = domain.CreateInstanceAndUnwrap(@"C:\CustomAssembly.dll", "CustomObjects.Class1");
Type t = obj.GetType();
obj = (CustomObjects.Class1)obj;
To make the problem more hard to diagnose if I created a new AppDomain and then created the type in the new AppDomain: what do you know, no problem! After careful inspection I noticed two instances of CustomAssembly.dll loaded at different offsets within the domain. Turns out the reference in my project for CustomAssembly and the path I was passing into CreateInstance pointed to two different physical files. Change the call to CreateInstance so it passes in the path that is referenced in the assembly and you're problem's solved.