Casting Problem when loading from dll
Hi
I am trying to load at runtime a class from a dll,
knowing an interface that the class implements.
I can load and create an instance of that class,
but only as an Object... I cannot convert it to
my interface.
The error is: System.InvalidCastException
The code is:
Assembly a=Assembly.LoadFrom(("a.dll");
Type theType = a.GetType("Type1");
Type interfaceType=theType.GetInterface("iType1");
Console.WriteLine("implements {0}",interfaceType);
Object o=Activator.CreateInstance(theType);
Console.WriteLine("loaded as an object: {0}",o);
iType1 i = (iType1) o;
Console.WriteLine(i);
Both the dll and the exe have the same namespace,
and they both know the interface iType1. And both
the interface and the class are public...
Thanks in advance,
YES, please somebody help
I have been having the exact same problem. I didn't have the same interface defined twice in the two assemblies, but I referenced the dll assembly and used the interface referenced in the dll assmbly for casting. I still got the casting error. Do the interface and class have to be in the same namespace? Any other helpful infromation would be appreciated. Thanks, Marko
thanks robert, but still...
here is my class:
namespace ComponentLibrary1
{
/// <summary>
/// Summary description for Class1.
/// </summary>
public class Component1: object, ILayoutComponent
{
public Component1()
{
MessageBox.Show("Hello");
}
void ILayoutComponent.Calculate()
{
}
}
}
here is my interface:
namespace ComponentLibrary1
{
public interface ILayoutComponent
{
void Calculate();
}
}
this builds into ComponentLibrary1.dll.
Here is my usage:
Assembly asm;
asm = Assembly.LoadFrom("..\\..\\..\\ComponentLibrary1\\bin\\Debug\\ComponentLibrary1.dll");
object obj = asm.CreateInstance("ComponentLibrary1.Component1");;
ILayoutComponent lc = (ComponentLibrary1.ILayoutComponent)obj;
lc.Calculate();
The DLL is specified in the exe assemnbly as a reference.
Note that I pruposly didn't new it from the reference since I want to specify the implementation to be loaded at runtime through a path string.
I hope this clarifies the situation and somebody can tell me what's wrong. Basically I want to have an interface in my exe that I can use to communicate to a dll library of implementations of this interface, but I wan't to be able to specify the dll at runtime. Typical add-in design.
Thanks in advance,
Marko