0
我試圖編寫某種插件框架......問題是: 我想使用插件中的方法作爲主機應用程序中控件的事件處理程序,並防止將插件程序集加載到主要appdomain。下面的代碼原因plugin.dll被加載到主要的AppDomain =(是否有任何其他方式做到這一點C#插件和事件處理程序
主機應用程序:
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 Instance
{
get { return _instance; }
}
}
插件:
[Serializable]
public class Test
{
public void TestEventHandler(object sender, System.EventArgs e)
{
MessageBox.Show("Pingback from plugin");
}
}
當有很多已經可用的時候編寫自己的框架的任何理由?例如,您需要MEF不提供什麼? – 2010-09-15 16:46:41