加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – MEF导入无法按预期工作

发布时间:2020-12-15 22:15:28 所属栏目:百科 来源:网络整理
导读:我有两个出口类: [Export(typeof(Mod))]public class CoreMod : Mod{ [ImportingConstructor] public CoreMod() { //here goes my constructor }}[Export(typeof(Mod))]public class AnotherMod : Mod{ [ImportingConstructor] public AnotherMod() { //her
我有两个出口类:

[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为null).我究竟做错了什么?

解决方法

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读