MEF Import没有按预期工作

本文关键字:工作 Import MEF | 更新日期: 2023-09-27 17:53:47

我有两个导出类:

[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加载mod:

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 Import没有按预期工作

我认为正在发生的事情是你有你的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();
    }
}