I have different class libraries that each implement an interface IImportCharacter. In my main app, the user selects a DLL and the app needs to check if the library implements the interface and then instantiate the class in the library which implements it. I’m trying to use reflection to do this but I keep getting:
Unable to cast object of type ‘CustomCharacter.Ogre’ to type
‘MainGame.IImportCharacter’.
Assembly assembly = assemblyPath;
foreach (Type type in assembly.GetTypes())
{
IImportCharacter instance = null;
if (type.GetInterface("IImportCharacter") != null)
{
//exception thrown at this line
instance = (IImportCharacter)Activator.CreateInstance(type);
}
}
I’ve copied the same IImportCharacter file into the main project, otherwise the compiler complains it doesn’t know what IImportCharacter is. I think this might be causing the problem since it’s not the same one being dynamically loaded. How can I fix this?
Yes, I think the interface you’re casting to is a different type with the same name. Why don’t you move IImportCharacter to a shared assembly that you can reference both from your code and the one you’re loading, since it’s your interface?
Otherwise, try using
Convert.ChangeType()with the dynamically loaded interface on your dynamically loaded type.