C#插件使用MarshalByRefObject创建多个副本

时间:2013-10-28 12:50:57

标签: c# plugins marshalbyrefobject

我正在整理一个包含这些要求的插件框架:

  • 随意加载/卸载插件
  • 在加载的插件中调用方法
  • 将插件中的回调事件提升为所有者

为此,我创建了一个新的AppDomain,并将插件程序集加载到此。

到目前为止我的实现工作达到了一定程度,但我相信我正在本地appDomain和新的AppDomain中创建插件实例。

首先加载时,我会收到重复的回调消息。当我多次加载/卸载时,我会将多个回调消息添加到列表中。这告诉我,我不仅远程加载插件程序集,而且还在本地加载插件程序集,因此我的“卸载”机制不能按照我的意愿运行。如果有人能告诉我哪里出错了,我将不胜感激。

我也理解我需要考虑插件的“生命周期”,但不知道在哪里实现它。

感谢。

(1)我有一个插件界面

public interface IPlugin
{
    string Name();
    string Version();
    string RunProcess();

    // custom event handler to be implemented, event arguments defined in child class
    event EventHandler<PluginEventArgs> CallbackEvent;
    //event EventHandler<EventArgs> CallbackEvent;
    void OnProcessStart(PluginEventArgs data);
    void OnProcessEnd(PluginEventArgs data);
}

(2)自定义事件args

[Serializable]
public class PluginEventArgs : EventArgs
{
    public string ResultMessage;
    public string executingDomain;

    public PluginEventArgs(string resultMessage = "")
    {
        // default empty values allows us to send back default event response
        this.ResultMessage = resultMessage;
        this.executingDomain = AppDomain.CurrentDomain.FriendlyName;
    }
}

(3)示例插件类实现

 [Serializable]
    public class Plugin_1 : IPlugin
    {
        System.Timers.Timer counter;
        int TimerInterval;
        string PluginName = "My plugin";

        public string Name()
        {
            return "CMD";
        }

        public bool Start()
        {
            OnStart(new PluginEventArgs());
            RunProcess();
            return true;
        }

        // OnTimer event, process start raised, sleep to simulate doing some work, then process end raised
        public void OnCounterElapsed(Object sender, EventArgs e)
        {
            OnProcessStart(new PluginEventArgs());
            OnProcessEnd(new PluginEventArgs());
            Stop();
        }

        public bool Stop()
        {
            // simulate waiting for process to finish whatever its doing....
            if (counter != null)
            {
                counter.Stop();
                OnStop(new PluginEventArgs());
            }
            return true;
        }

        public string RunProcess()
        {
            TimerInterval = 2000;
            if (counter == null){ 
                counter = new System.Timers.Timer(TimerInterval); 
                }
            else { 
                counter.Stop();
                counter.Interval = TimerInterval;
                }

            counter.Elapsed += OnCounterElapsed;
            counter.Start();
            return "";
        }

        public event EventHandler<PluginEventArgs> CallbackEvent;

        void OnCallback(PluginEventArgs e)
        {
            if (CallbackEvent != null)
            {
                CallbackEvent(this, e);
            }                    
        }


        public void OnProcessStart(PluginEventArgs Data)
        {
            OnCallback(new PluginEventArgs(Data.executingDomain + " - " + PluginName + " started"));   
        }

        public void OnProcessEnd(PluginEventArgs Data)
        {
            OnCallback(new PluginEventArgs(Data.executingDomain + " - " + PluginName + " ended"));   
        }

(4)我有一个加载/卸载的插件管理器

public bool LoadPlugin() {      尝试     {     Domain_Command = AppDomain.CreateDomain(“Second_domain”);     command_loader =(ProxyLoader)Domain_Command.CreateInstanceAndUnwrap(“PluginMgr”,“PluginMgr.Method”);     Plugins.AddPlugin(command_loader.LoadAndExecute(“APluginName”,Plugins.ProxyLoader_RaiseCallbackEvent),SomePluginType,false);
    返回true;
    }      catch(Exception ex)      {          string message = ex.Message;          返回false;      } }

(5)我的“ProxyLoader”将插件加载到单独的AppDomain

public class ProxyLoader : MarshalByRefObject
{
    public AssemblyInstanceInfo LoadAndExecute(string assemblyName, EventHandler<PluginContract.PluginEventArgs> proxyLoader_RaiseCallbackEvent)
    {
        AssemblyInstanceInfo AInfo = new AssemblyInstanceInfo();
        //nb: this AppDomain.CurrentDomain is in its own context / different from the caller app domain?
        Assembly pluginAssembly = AppDomain.CurrentDomain.Load(assemblyName);
        foreach (Type type in pluginAssembly.GetTypes())
        {
            if (type.GetInterface("IPlugin") != null)
            {
                object instance = Activator.CreateInstance(type, null, null);
                AInfo.ObjectInstance = instance;
                string s = ((PluginContract.IPlugin)instance).RunProcess(); // main procedure
                AInfo.ASM = pluginAssembly;
                ((PluginContract.IPlugin)instance).CallbackEvent += proxyLoader_RaiseCallbackEvent;
                ((PluginContract.IPlugin)instance).Start();
                instance = null;
            }
        }
        return AInfo;
    }
}

(6)我有一个回调插入

public event EventHandler<PluginContract.PluginEventArgs> Callback;

void OnCallback(PluginContract.PluginEventArgs e)
        {
            if (Callback != null)
            {
                Callback(this, e);
            }
        }

(7)调用(在加载程序集时在ProxyLoader中引用)

public void ProxyLoader_RaiseCallbackEvent(object source, PluginContract.PluginEventArgs e)
{
    OnCallback(new PluginContract.PluginEventArgs(str));
}

0 个答案:

没有答案