开发者

C# Plugins and event handlers

I'm trying to write some kind of plugin framework... The problem is: I want to use methods from plugins as event handlers for controls in the host application and prevent loading plugin assembly into the main appdomain. The following code causes plugin.dll to be loaded into the main appdomain =( Is there any other way to do that?

Host application:

public partial class Form1 : Form
{
    private AssemblyLoader _aLoader = null;

    public Form1()
    {
        InitializeComponent();

        AppDomain _domain = AppDomain.CreateDomain("Remote Load");
        _aLoader = (AssemblyLoader)_domain.CreateInstanceAndUnwrap(
                                 "Loader", "Loader.AssemblyLoader");

        _aLoader.Load();

        EventHandler eh = (EventHandler)Delegate.CreateDelegate(typeof(EventHandler), _aLoader.Instance, _aLoader.Method);

        button1.Click += eh;
    }
}

AssemblyLoader:

[Serializable]
public class AssemblyLoader : MarshalByRefObject
{
    object _instance = null;
    MethodInfo _method = null;

    public void Load()
    {
        Assembly _assembly = Assembly.LoadFile(Environment.CurrentDirectory + @"\Plugin.dll");
        Type _type = _assembly.GetType("Plugin.Test");
        _instance = Activator.CreateInstance(_type);
        _method = _instance.GetType().GetMethod("TestEventHandler");
    }

    public MethodInfo Method
    {
        get { return _method; }
    }

    public object Ins开发者_如何学Ctance
    {
        get { return _instance; }
    }
}

Plugin:

[Serializable]
public class Test
{
    public void TestEventHandler(object sender, System.EventArgs e)
    {
        MessageBox.Show("Pingback from plugin");
    }      
}


Don't waste your valuable time writing your own framework. Use an existing:

http://clraddins.codeplex.com/

http://blogs.msdn.com/b/clraddins/

Also check this answer that talk about the comparison with MAF & MEF, the two popular frameworks.

Those framework as well written, they are .NET standard and well supported.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜