基于 MEF 的插件系统无法实例化我的插件



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

下面是我的代码片段:

Plugin-Loader:

    [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");
    }
    ...
}

测试工作样本

用PluginNameSpace命名空间中的代码编译类库,并将其放在console app 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");
        }
    }
}

相关内容

  • 没有找到相关文章

最新更新