I'm trying to load some .dll files dynamically. The Files are Plugins (self-written for now) which have at least one class that implements MyInterface
. For each file I'm doing the following:
Dictionary<MyInterface, bool> _myList;
// ...code
Assembly assembly = Assembly.LoadFrom(currentFile.FullName);
foreach (Type type in assembly.GetTypes())
{
var myI = type.GetInterface("MyInterface");
if(myI != null)
{
if ((myI.Name == "MyInterface") && !type.IsAbstract)
{
var p = Activator.CreateInstance(type);
_myList.Add((MyInterface)p, true);
}
}
}
Running this causes a cast exception, but I can't find a workaround. Anyway I am wondering why this doesn't work at all. I'm looking for a solution in .NET Framework 3.5.
Another thing that happened to me was getting null
in p
after running the following at the point before adding a new entry to _myList
in the code above:
var p = type.InvokeMember(null, BindingFlags.CreateInstance, null,
null, null) as MyInterface;
This code was the first attempt on loading the plugins, I didn't find out why p
was null
yet.
I hope someone can lead me to the right way :)
There's much easier way to check if your type can be casted to your interface.
Assembly assembly = Assembly.LoadFrom(currentFile.FullName);
foreach (Type type in assembly.GetTypes())
{
if(!typeof(MyInterface).IsAssignableFrom(type))
continue;
var p = Activator.CreateInstance(type);
_myList.Add((MyInterface)p, true);
}
If IsAssignableFrom
is false, there's something wrong with your inheritance, which is most likely cause of your errors.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With