【问题标题】:Retrieve a list of object implementing a given interface检索实现给定接口的对象列表
【发布时间】:2009-10-13 22:22:57
【问题描述】:

简介

我正在我的应用程序中构建插件架构。插件实现一个给定的接口IBasePlugin,或者从基本接口继承的一些其他接口:

interface IBasePlugin
interface IMainFormEvents : IBasePlugin

宿主正在加载插件程序集,然后创建实现 IBasePlugin 接口的任何类的适当对象..

这是加载插件和实例化对象的类:

 public class PluginCore
 {
     #region implement singletone instance of class
     private static PluginCore instance;
     public static PluginCore PluginCoreSingleton
     {
         get
         {
             if (instance == null)
             {
                 instance = new PluginCore();
             }
             return instance;
         }
     }
     #endregion

     private List<Assembly> _PlugInAssemblies = null;
     /// <summary>
     /// Gets the plug in assemblies.
     /// </summary>
     /// <value>The plug in assemblies.</value>
     public List<Assembly> PlugInAssemblies
     {
         get
         {
             if (_PlugInAssemblies != null) return _PlugInAssemblies;

             // Load Plug-In Assemblies
             DirectoryInfo dInfo = new DirectoryInfo(
                 Path.Combine(
                     Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                     "Plugins"
                     )
                 );
             FileInfo[] files = dInfo.GetFiles("*.dll");
             _PlugInAssemblies = new List<Assembly>();
             if (null != files)
             {
                 foreach (FileInfo file in files)
                 {
                     _PlugInAssemblies.Add(Assembly.LoadFile(file.FullName));
                 }
             }

             return _PlugInAssemblies;
         }
     }

     List<IBasePlugin> _pluginsList = null;
     /// <summary>
     /// Gets the plug ins instances.
     /// all the plugins are being instanciated ONCE when this if called for the first time
     /// every other call will return the existing classes.
     /// </summary>
     /// <value>The plug ins instances.</value>
     public List<IBasePlugin> PlugInInstances
     {
         get
         {
             if (_pluginsList != null) return _pluginsList;

             List<Type> availableTypes = new List<Type>();

             foreach (Assembly currentAssembly in this.PlugInAssemblies)
                 availableTypes.AddRange(currentAssembly.GetTypes());

             // get a list of objects that implement the IBasePlugin
             List<Type> pluginsList = availableTypes.FindAll(delegate(Type t)
             {
                 List<Type> interfaceTypes = new List<Type>(t.GetInterfaces());
                 return interfaceTypes.Contains(typeof(IBasePlugin));
             });

             // convert the list of Objects to an instantiated list of IBasePlugin
             _pluginsList = pluginsList.ConvertAll<IBasePlugin>(delegate(Type t) { return Activator.CreateInstance(t) as IBasePlugin; });

             return _pluginsList;
         }
     }

问题

目前,任何支持插件的模块都使用 PlugInInstances 属性来检索 IBasePlugins 列表。然后它迭代查询谁正在实现给定子接口的对象。

foreach (IBasePlugin plugin in PluginCore.PluginCoreSingleton.PlugInInstances)
{
     if (plugin is IMainFormEvents)
     {
         // Do something
     }
 }

我想通过拥有一个接收给定子接口的函数来改进这项技术,并返回这些接口的列表。问题是调用者不应进行强制转换。

伪代码:

void GetListByInterface(Type InterfaceType, out List<InterfaceType> Plugins)

您对如何实现这一点有什么建议吗?

【问题讨论】:

  • 您是否考虑过使用 Microsoft 的托管可扩展性框架? codeplex.com/MEF
  • @TrueWill:我有在家里做这件事的代码。几个小时后我会去看看。
  • 使用类型接口的哈希图创建一个对象查找树。
  • @TrueWill:MEF 看起来很有趣,可能会比我问的更多。但就目前而言,我仍然想为我所问的问题找到解决方案。

标签: c# generics architecture plugins interface


【解决方案1】:

你可以试试这样的:

void GetListByInterface<TInterface>(out IList<TInterface> plugins) where TInterface : IBasePlugin
{
  plugins = (from p in _allPlugins where p is TInterface select (TInterface)p).ToList();
}

【讨论】:

  • @Andrew:谢谢,正是我想要的。虽然我必须在没有 LINQ 的情况下实现它,因为我有 .NET 2 合规性。
  • 我应该说 _allPlugins.OfType() 但这并不重要,因为你没有使用 linq。
【解决方案2】:

我在锦标赛系统中使用了类似的方法。

您可以在此处查看源代码: http://tournaments.codeplex.com/SourceControl/ListDownloadableCommits.aspx

在trunk/TournamentApi/Plugins/PluginLoader.cs 中,我定义了加载任意程序集插件所需的方法。


我使用的想法是可以找到、实例化和调用 Plugin-Factory-Enumerator 类以生成插件工厂实例。

这是代码的核心:

List<IPluginFactory> factories = new List<IPluginFactory>();

try
{
    foreach (Type type in assembly.GetTypes())
    {
        IPluginEnumerator instance = null;

        if (type.GetInterface("IPluginEnumerator") != null)
        {
            instance = (IPluginEnumerator)Activator.CreateInstance(type);
        }

        if (instance != null)
        {
            factories.AddRange(instance.EnumerateFactories());
        }
    }
}
catch (SecurityException ex)
{
    throw new LoadPluginsFailureException("Loading of plugins failed.  Check the inner exception for more details.", ex);
}
catch (ReflectionTypeLoadException ex)
{
    throw new LoadPluginsFailureException("Loading of plugins failed.  Check the inner exception for more details.", ex);
}

return factories.AsReadOnly();

【讨论】:

    【解决方案3】:

    我会使用 IOC 容器来执行插件查找。 MEF 可能有点多,但 StructureMap 是一个单独的 DLL,并且开箱即用地内置支持。

    您可以扫描文件夹以查找包含实现接口的对象的程序集,并将它们轻松加载到您的应用程序中。 StructureMap on SourceForge

    ObjectFactory 的 Configure 方法中的扫描示例:

            Scan(scanner =>
            {
                string assemblyPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
    
                scanner.AssembliesFromPath(assemblyPath, assembly => { return assembly.GetName().Name.StartsWith("Plugin."); });
    
                scanner.With(typeScanner);
            });
    

    类型扫描器实现 ITypeScanner 并且可以检查类型以检查该类型是否可分配给相关接口类型。随附的文档链接中有很好的示例。

    【讨论】:

      猜你喜欢
      • 2017-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-06
      • 1970-01-01
      • 2013-09-05
      相关资源
      最近更新 更多