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

时间:2015-09-02 13:40:17

标签: c# plugins reflection mef

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

以下是我的代码片段:

插件-装载机:

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

1 个答案:

答案 0 :(得分:0)

经过测试的工作样本。

使用PluginNameSpace命名空间内的代码编译类库,并将其放在“Test”文件夹中,该文件夹位于console app exe文件夹中。

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