简体   繁体   English

c#插件事件处理

[英]c# Plugin Event Handling

I have written a plugin system that uses an interface and for any plugins that meet this contract are loaded at runtime into the main system. 我已经编写了一个使用接口的插件系统,并且所有符合此合同的插件都在运行时加载到主系统中。

The plugin effectively returns a TabPage that is slotted into the main app, and is controlled fromwithin the plugin dll. 该插件有效地返回一个TabPage,该TabPage插入了主应用程序,并从插件dll中进行控制。

If an error occurs within the plugin, the standard Windows error message shows. 如果插件内发生错误,则显示标准Windows错误消息。 What I want to do it create an event that returns the error message so I can display it in the area I have reserved for text. 我要执行的操作将创建一个返回错误消息的事件,以便将其显示在为文本保留的区域中。

Do I need to keep a track of all attached plugin/interface instances to be able to set up an event to monitor each one? 我是否需要跟踪所有连接的插件/接口实例,以便能够设置一个事件来监视每个插件/接口实例?

At present, my system loops through the dll's within the app folder and those that meet the interface contract are loaded up, the actual instance of the interface is discarded each time as control is then handed over to the dll via button events that are loaded with the TabPage and handled within the plugin. 目前,我的系统遍历app文件夹中的dll,并且加载了符合接口协定的dll,每次将控件的实际实例都丢弃时,然后将控件通过加载的按钮事件移交给dll。 TabPage并在插件中处理。

I hope this all makes sense. 我希望这一切都有意义。

您不需要保留对插件类的引用,只需在启动事件时向事件添加一个委托,之后就不再需要引用。

You could add an event to your plugin contract: 您可以将事件添加到插件合同中:

public interface IPlugin
{
    event EventHandler<ErrorEventArgs> Error;

    void Initialise();
}

That way, any host can subscribe to that event when errors occur within the plugin: 这样,当插件内发生错误时,任何主机都可以订阅该事件:

public class MyPlugin : IPlugin
{
    public event EventHandler<ErrorEventArgs> Error;

    public void Initialise()
    {
        try
        {

        }
        catch (Exception e)
        {
            OnError(new ErrorEventArgs(e));
        }
    }

    protected void OnError(ErrorEventArgs e)
    {
        var ev = Error;
        if (ev != null)
            ev(this, e);
    }
}

If I have followed you post correctly, this is how I would go about doing it. 如果我正确地按照您的要求发帖,这就是我要做的。

In the plugin interface (Lets say IPlugin) you will need to declare an event. 在插件接口(假设为IPlugin)中,您需要声明一个事件。

public delegate void ShowErrorEventHandler(string errorMessage);
public interface IPlugin
{
    event ShowErrorEventHandler ShowError;
}

Then when you load your plugins, for each one just subscribe to it's ShowError event, for example: 然后,当您加载插件时,只需为每个插件订阅ShowError事件,例如:

...
foreach(var plugin in plugins)
{
    plugin.ShowError += MainForm_ShowError;
}
...

private void MainForm_ShowError(string errorMessage)
{
    // Do something with the error... stick it in your reserved area
    txtReservedArea.Text = errorMessage;
}

Hope this helps 希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM