【问题标题】:MEF based plugin system can't instance my plugins基于 MEF 的插件系统无法实例化我的插件
【发布时间】:2015-09-02 13:40:16
【问题描述】:

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

这是我的代码的 sn-p:

插件加载器:

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

【问题讨论】:

  • 我在控制台应用程序中复制了您的代码,并且没有问题。

标签: c# plugins reflection mef


【解决方案1】:

经过测试的工作样本。

使用 PluginNameSpace 命名空间内的代码编译类库,并将其放置在控制台应用程序 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");
        }
    }
}

【讨论】:

  • 你看过我的帖子吗?在这篇文章中,我说过,我的插件列在 AggregateCatalog 中。只有 ComposeContainer 不能组成这些部分。我的插件是一个独立的库。我自己解决了这个问题。接口 IFetchService 应由自己的库分隔。这个库应该被双方引用。现在我的插件已加载并实例化。
猜你喜欢
  • 1970-01-01
  • 2015-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-11
  • 2017-02-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多