I'm developing a program that uses plugins. All plugins are classes that inherits from KrotAPI.IKrotAPI interface. The interface is stored in krotapi.cs file, that is common for both host's csproj and every plugins' *.csproj.
The host loads plugins using this code
dynamic LoadPlugin(Assembly asm)
{
foreach (Type type in asm.GetTypes())
{
if (type.GetInterface("KrotAPI.IKrotPlugin") != null)
{
PluginType = type;
dynamic inst = Activator.CreateInstance(type);
KrotAPI.IKrotPlugin inst2 = inst as KrotAPI.IKrotPlugin;
if (inst2 == null) return inst;
Console.WriteLine("Link to API is set up.");
return inst2;
}
}
throw new Exception("There are no valid plugin(s) in the DLL.");
}
The inst2 is always null, and I am forced to use slow and buggy dynamic calls. How to make it like inst, but with KrotAPI.IKrotPlugin type?
Second question on almost same topic. Some plugins' functions returns an result of type KrotAPI.FindData (it's an structure, that is stored in above krotapi.cs file). But i cannot access it:
dynamic fd = new KrotAPI.FindData();
if (NextItemInfo != null) //NextItemInfo is an instance of that struct
fd = NextItemInfo;
listBox1.Items.Add(fd.FileName);
On last row NET Framework throws this exception:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException 'System.ValueType' does not contain a definition for 'FileName'
however the FileName field is hardcoded in the struct and certainly not a null, or
Microsoft.CSharp.RuntimeBinder.RuntimeBinderInternalCompilerException An unexpected exception occurred while binding a dynamic operation
if I replace the last line with KrotAPI.FindData fd2 = (KrotAPI.FindData) fd; listBox1.Items.Add(fd2.FileName);.
WTF?
You have your IKrotAPI interface defined in your host and your plugins. This means that they are not the same interface. The containing assembly is part of the interface's full identity. Each of your plugins is actually implementing an interface that is defined within it's own assembly, which is not the same interface that is defined within the host assembly.
There are two ways to solve this:
IKrotAPI interface.KrotAPI.FindData) that are common to both host and server.I personally prefer the second approach. It allows you to upgrade your host assembly without invalidating the existing plugins. To use a common naming convention for this sort of assembly, this third assembly might be called something like KrotAPI. I tend to think of an "API" as the set of interfaces and data types that someone (i.e. a plugin developer) would code against, but all actual runnable code would, in your case, be in either the host or the plugin.
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