MEF导入未按预期工作

4

我有两个带有导出的类:

[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在另一个程序集中,它们都引用了这个程序集。
在我的应用程序中,我有一个类,试图通过MEF加载Mods:

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为空)。我做错了什么?

我认为你的问题标题应该是“MEF导入不像预期的那样工作”。我非常确定整个MEF都在工作。 - Maarten
1个回答

1

我认为正在发生的事情是你将CompositionContainer作为函数变量而不是类变量。此外,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();
    }
}

谢谢,整个问题都在于 static 关键字。很奇怪,但我写代码之前学习的示例使用了静态集合。也许是较旧版本的MEF。 - Inky Quill
按照答案中的方法做了一切,但对我来说没有用,每次IEnumerable都是null。 - alalambda

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接