2015-09-02 52 views
0

我已经实现了一个基于C# with MEF的非常小的插件系统。问题是,我的插件没有实例化。在Aggregate-Catalog我可以看到my plugin listed。但是,在我编写这些部分之后,插件列表中没有插件,我做错了什么?基于MEF的插件系统不能插件我的插件

这里是我的代码片段:

插件-装载机:

[ImportMany(typeof(IFetchService))] 
    private IFetchService[] _pluginList; 
    private AggregateCatalog _pluginCatalog; 
    private const string pluginPathKey = "PluginPath"; 
    ... 

    public PluginManager(ApplicationContext context) 
    { 
     var dirCatalog = new DirectoryCatalog(ConfigurationManager.AppSettings[pluginPathKey]); 
     //Here's my plugin listed... 
     _pluginCatalog = new AggregateCatalog(dirCatalog); 

     var compositionContainer = new CompositionContainer(_pluginCatalog); 
     compositionContainer.ComposeParts(this); 
    } 
    ... 

这里,插件本身:

[Export(typeof(IFetchService))] 
public class MySamplePlugin : IFetchService 
{ 
    public MySamplePlugin() 
    { 
     Console.WriteLine("Plugin entered"); 
    } 
    ... 
} 
+0

我复制你的代码中的控制台应用程序和它的工作没有问题。 –

回答

0

测试工作的样品。

用PluginNameSpace命名空间内的代码编译类库,并将其放置到将放在控制台应用程序exe文件夹内的'Test'文件夹中。

using System; 
using System.ComponentModel.Composition; 
using System.ComponentModel.Composition.Hosting; 
using System.IO; 
using System.Reflection; 
using ConsoleApplication; 

namespace ConsoleApplication 
{ 
    public interface IFetchService 
    { 
     void Write(); 
    } 

    class PluginManager 
    { 
     [ImportMany(typeof(IFetchService))] 
     public IFetchService[] PluginList; 

     public PluginManager() 
     { 
      var dirCatalog = new DirectoryCatalog(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\Test"); 

      var pluginCatalog = new AggregateCatalog(dirCatalog); 
      var compositionContainer = new CompositionContainer(pluginCatalog); 
      compositionContainer.ComposeParts(this); 
     } 
    } 

    class Program 
    { 
     static void Main(string[] args) 
     { 
      var pluginManager = new PluginManager(); 

      foreach (var fetchService in pluginManager.PluginList) 
      { 
       fetchService.Write(); 
      } 

      Console.ReadKey(); 
     } 
    } 
} 

// Separate class library 
namespace PluginNameSpace 
{ 
    [Export(typeof(IFetchService))] 
    public class MySamplePlugin : IFetchService 
    { 
     public void Write() 
     { 
      Console.WriteLine("Plugin entered"); 
     } 
    } 
} 
+0

您是否看过我的文章?在这篇文章中,我说过,我的插件已列在AggregateCatalog中。只有ComposeContainer不能编写这些部分。我的插件是一个单独的库。我已经通过myselfe解决了这个问题。接口IFetchService应该由自己的库分开。这个库应该从双方引用。现在我的插件被加载并实例化。 – user3149497