我有两个出口类:
[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(); } }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。