没有加载我的插件

本文关键字:插件 我的 加载 | 更新日期: 2023-09-27 18:10:42

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

没有加载我的插件

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

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

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

现在,您可以让DI容器为您组成这个SomeClass的实例。您将看到它的pluginList字段包含您的插件引用。