0

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

主机应用:

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;

    }

}
}

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

4

1 回答 1

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

于 2013-04-22T10:27:01.553 回答