【问题标题】:MEF isn't loading my pluginMEF 没有加载我的插件
【发布时间】:2015-09-01 20:47:43
【问题描述】:

我在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】:

你做错了。 _pluginList 字段的 ImportMany 属性没有任何意义,因为插件管理器实例将由您创建,而不是由 DI 容器创建。

你必须创建另一个类来导入你所有的插件。

[Export]
class SomeClass
{
    readonly IFetchService[] pluginList;

    [ImportingConstructor]
    public SomeClass([ImportMany(typeof(IFetchService))]IFetchService[] pluginList)
    {
        this.pluginList = pluginList;
    }
}

现在,您可以让 DI 容器为您编写此 SomeClass 的实例。您会看到它的 pluginList 字段包含您的插件引用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-14
    • 2010-11-15
    • 2012-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多