A
A
ATauenis2017-02-19 13:35:07
OOP
ATauenis, 2017-02-19 13:35:07

How to forward an interface through dynamic in C#?

Good day! I am writing a program with plugins. All plugins are classes that implement the KrotAPI.IKrotPlugin interface. The KrotAPI namespace is taken from the krotapi.cs file common to all plugin projects. The same file is attached to the host project. The procedure for loading a plugin by a host is as follows:

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("Есть привязка к стандартному API.");
          return inst2;
        }
      }
      throw new Exception("Нет плагинов Крота в сборке.");
    }

What is the problem. The plugin can only be loaded into the inst variable, null is returned in inst2 despite the fact that Activator.CreateInstance(type) returns a class inheriting from KrotAPI.IKrotPlugin. Apparently the CLR does not like the fact that the class interface is in a different assembly, although according to the source it is identical to the interface of the same name from the host assembly. Is there any way to convince the CLR that inst is KrotAPI.IKrotPlugin? Those. do duck typing.
And the second question, immediately. If this is beyond the power of the .NET Framework (4.0), then how to make it possible for the plugin to call such a function in the host:
int HostEar(string Command, Dictionary<string, object> Arguments, out object Result)

? If you drive through the Delegate, then the plug goes in the out transfer, the compiler does not accept the out word, and without it, a runtime error occurs, they say, a function with so many arguments was not found.
The "static" delegate (delegate with a small letter), perfectly passing between classes inside the host, when passed to the plugin through a method or property, destroys the host with such curses:
Microsoft.CSharp.RuntimeBinder.RuntimeBinder
Internal Compiler Exception
An unexpected exception occurred while binding a dynamic operation

. That is, too, duck typing does not work, even when I place this delegate in krotapi.cs.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
ATauenis, 2017-02-22
@ATauenis

Solved by statically linking both the host and the plugins, with an assembly containing the interface.
stackoverflow.com/questions/42376539/how-to-access...

D
d-stream, 2017-02-19
@d-stream

It may not be too late on the topic of plugins: https://msdn.microsoft.com/ru-ru/library/dd460648(... https://habrahabr.ru/post/83928/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question