C#插件和主机应用程序之间的通信

时间:2013-04-22 10:11:27

标签: c# plugins interface communication

我正在编写基于插件的应用程序。

主持人申请:

namespace CSK
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{

    public MainWindow()
    {                  
        InitializeComponent();
        LoadPlugins();

    }

    public void LoadPlugins()
    {
        DirectoryInfo di = new DirectoryInfo("./Plugins");

        foreach (FileInfo fi in di.GetFiles("*_Plugin.dll"))
        {
            Assembly pluginAssembly = Assembly.LoadFrom(fi.FullName);

            foreach (Type pluginType in pluginAssembly.GetExportedTypes())
            {

                if (pluginType.GetInterface(typeof(MainInterface.PluginHostInterface).Name) != null)
                {
                    MainInterface.PluginHostInterface TypeLoadedFromPlugin = (MainInterface.PluginHostInterface)Activator.CreateInstance(pluginType);
                    MainInterface.IMother mother = new ApiMethods(this);
                    TypeLoadedFromPlugin.Initialize(mother);
                }

            }
        }
    }
}

接口:

namespace MainInterface
{
public interface PluginHostInterface
{
    void Initialize(IMother mother);
}

public interface IMother
{
    MenuItem addMenuItem(String header, String name);
    MenuItem addSubMenuItem(MenuItem menu, String header, String name);
    Boolean receiveMessage(String message, String from);
    Boolean addContact(String name, String status, String proto, String avatar = "av");
}
}

测试插件:

namespace Plugin_Test
{
public class MainClass : MainInterface.PluginHostInterface
{
    private MainInterface.IMother CSK;

    public void Initialize(MainInterface.IMother mainAppHandler)
    {
        CSK = mainAppHandler;

    }

}
}

现在,我想从宿主应用程序中执行插件测试中的一些方法。当然,会有很多插件,并不是每个插件都包含指定的方法。我试图使用事件但没有成功。知道怎么做吗?

1 个答案:

答案 0 :(得分:1)

带事件的课程:

public class EventProvidingClass {

    public event EventHandler SomeEvent;

    public void InvokeSomeEvent() {
        if(SomeEvent != null) SomeEvent.Invoke(this, new EventArgs());
    }

}

您的插件界面:

public interface PluginHostInterface
{
    void Initialize(IMother mother);
    void InitializeEvents(EventProvidingClass eventProvider);
}

插件类:

public class MainClass : MainInterface.PluginHostInterface
{
    private MainInterface.IMother CSK;

    public void Initialize(MainInterface.IMother mainAppHandler)
    {
        CSK = mainAppHandler;
    }

    public void InitializeEvents(EventProvidingClass eventProvider)
    {
        eventProvider.SomeEvent += someEventHandler;
    }

    private void someEventHandler(object sender, EventArgs e)
    {

    }
}

然后在InitializeEvents函数后调用Initialize。 当然你可以把事件放在你想要的地方,你只需要确保它们可以用于插件,以便插件可以分配它的EventHandlers