MEF 导入未按预期工作

MEF Import doesn't work as expected

我有两个 class 出口:

[Export(typeof(Mod))]
public class CoreMod : Mod
{
    [ImportingConstructor]
    public CoreMod()
    {
      //here goes my constructor
    }
}

[Export(typeof(Mod))]
public class AnotherMod : Mod
{
    [ImportingConstructor]
    public AnotherMod()
    {
      //here goes my constructor
    }
}

CoreMod 在我的主程序集中,AnotherMod 在外部程序集中。 Mod 在另一个程序集中,他们都在引用它。
在我的应用程序中,我有一个 class 试图通过 MEF 加载模组:

class ModManager
{
    [ImportMany(typeof(Mod))]
    public static IEnumerable<Mod> Mods { get; set; }

    public List<Mod> LoadedMods { get; set; } 

    public ModManager()
    {
        AggregateCatalog catalog = new AggregateCatalog();
        catalog.Catalogs.Add(new AssemblyCatalog(typeof(CoreMod).Assembly));
        catalog.Catalogs.Add(new DirectoryCatalog(
            Path.GetDirectoryName(
                new Uri(Assembly.GetExecutingAssembly()
                               .CodeBase).LocalPath)));

        var container = new CompositionContainer(catalog);
        container.ComposeParts(this);

        LoadedMods = Mods.ToList();
    }
}

在我看来应该满足所有导入,但它仍然无法导入任何内容(Mods 为空)。我做错了什么?

我认为发生的事情是您将 CompositionContainer 作为函数变量而不是 class 变量。此外,MEF 不支持导入到静态变量。试试这个:

class ModManager
{
    [ImportMany(typeof(Mod))]
    public IEnumerable<Mod> Mods { get; set; }

    public List<Mod> LoadedMods { get; set; } 
    CompositionContainer _container;

    public ModManager()
    {
        AggregateCatalog catalog = new AggregateCatalog();
        catalog.Catalogs.Add(new AssemblyCatalog(typeof(CoreMod).Assembly));
        catalog.Catalogs.Add(new DirectoryCatalog(
            Path.GetDirectoryName(
                new Uri(Assembly.GetExecutingAssembly()
                               .CodeBase).LocalPath)));

        _container = new CompositionContainer(catalog);
        this._container.ComposeParts(this);

        this.LoadedMods = this.Mods.ToList();
    }
}