首先我们得让宿主程序保存已加载插件的引用,并能获取制定的插件引用,修改一下IAppContext接口,添加以下内容
//宿主程序需要保存所有插件的信息,以插件可以相互获得其他插件的引用
void AddService(string pluginName, IPlugIn plugin);
void RemoveService(string pluginName);
IPlugIn GetService(string pluginName);
//用来保存插件引用的列表
private Dictionary<string,IPlugIn> _Services = new Dictionary<string,IPlugIn>();
public void AddService(string pluginName, IPlugIn plugin)
{
this._Services.Add(pluginName,plugin);
}
public void RemoveService(string pluginName)
{
this._Services.Remove(pluginName);
}
public IPlugIn GetService(string pluginName)
{
IPlugIn plugin= null;
if(this._Services.TryGetValue(pluginName,out plugin))
return plugin;
else
return null;
}
//实现了contract里约定的方法,控制台上输出宿主程序的属性TextOut字符串
public void PrintToConsole()
{
IPlugIn plugin = m_App.GetService("ASimplePlugIn.PrintHelloWorld");
if(plugin==null)
Console.WriteLine("please load plugin named ASimplePlugIn first");
else
plugin.PrintToConsole();
}
代码下载:https://files.cnblogs.com/Pcant/SimplePlug-in3.rar