c# Plugin Event Handling

2019-04-16 05:45发布

问题:

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.

If an error occurs within the plugin, the standard Windows error message shows. 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.

I hope this all makes sense.

回答1:

You don't need to keep a reference to the plugin class, just add a delegate to the event when you start it up, after that you don't need the reference anymore.



回答2:

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);
    }
}


回答3:

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.

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:

...
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