我有两个出口类:
[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)。我做错了什么?
答案 0 :(得分: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();
}
}