///通用的加载插件的代码:转贴

///通用的加载插件的代码:
public class plugIn
{
 /**//// <summary>
 /// 动态装载并创建类型,该类型拥有指定接口
 /// </summary>
 /// <param name="className">类型名称</param>
 /// <param name="interfaceName">指定的接口名称</param>
 /// <param name="param">指定构造函数的参数(null或空的数组表示调用默认构造函数)</param>
 /// <returns>返回所创建的类型(null表示该类型无法创建或找不到)</returns>
 public static object LoadObject(string className, string interfaceName, object[] param)
 {
  try
  {
   Type t = Type.GetType(className);
             
   if ( t == null
    || !t.IsClass
    ||  !t.IsPublic
    ||  t.IsAbstract
    ||  t.GetInterface(interfaceName) == null)
   {
    return null;
   }

   object o = Activator.CreateInstance(t, param);
   if( o == null )
   {
    return null;
   }
   
   return o;
  }
  catch( Exception ex )
  {
   return null;
  }
 }
 //
 //  以后,我们就可以使用LoadObject载入任何所需的插件。
 //
 //  插件一般放在配置文件中,并由程序读入:

 //  配置文件举例(配置文件的使用参见我的相关随笔):
 //<?xml version="1.0" encoding="utf-8" ?>
 //<configuration>
 //    <configSections>
 //        <section name="Channels" type="Vmp.Configuration.ChannelsSectionHandler, Communication" />
 //    </configSections>
 //   
 //    <Channels>
 //        <channel
 //            ChannelType="Vmp.Communication.TcpChannel, Communication"
 //            TraceFile="d:/log/channel1.log"
 //            Port="2020" MaxConnections="300" BufferSize="2048"
 //        />
 //    </Channels>
 //</configuration>

// // 代码范例:
 private ArrayList channelsList = new ArrayList();

 private void  LoadChannels()
 {
  ArrayList channelsConfig = (ArrayList)ConfigurationSettings.GetConfig( "Channels" );
  foreach(Hashtable config in channelsConfig)
  {
   string channelType    = (string) config["ChannelType"];

   IChannel channel = (IChannel) CommonUtils.LoadObject(channelType, typeof(IChannel).FullName, new object[]{config});
   if(channel == null)
    continue;

   channelsList.Add(channel);
  }

// // 也可以遍历指定的插件目录,并载入所有符合要求的插件,例如:
         public IPlugin[] LoadAllPlugIn(string pluginDir)
         {
          // 设置默认的插件目录
          if(pluginDir == null || pluginDir == "")
           pluginDir = "./PlugIns";

          // 获取插件接口名称
          string interfaceName = typeof(IPlugin).FullName;

          // 用于存放插件的数组
          ArrayList arr = new ArrayList();

          // 遍历插件目录(假设插件为dll文件)
          foreach(string file in Directory.GetFiles(pluginDir, "*.dll"))
          {
           // 载入插件文件
           Assembly asm = Assembly.LoadFile(file);
           // 遍历导出的插件类
           foreach(Type t in asm.GetExportedTypes())
           {
            // 载入插件,如果插件不符合指定的接口,则返回null
            IPlugin plugin = LoadObject(t.FullName, interfaceName, null) as IPlugin;

            if(plugin != null)
             arr.Add(plugin);
           }
          }

          // 返回插件
          return (IPlugin[])arr.ToArray(typeof(IPlugin));
         }
}

posted on 2005-10-21 11:20  老代哥哥  阅读(207)  评论(0编辑  收藏  举报

导航