导入大量MEF加载合同两次

时间:2012-11-03 23:11:50

标签: c# .net wpf mef caliburn.micro

我有两个导出IScreen的类,但是当我使用

导入它时
[ImportMany(typeof(IScreen))]
private IEnumerable<Lazy<IScreen,IJIMSMetadata>> _modules;
public IEnumerable<Lazy<IScreen, IJIMSMetadata>> Modules
{
        get { return _modules; }
}

模块包含四个IScreen实例,但我只导出了两个。

这是容器

container = new CompositionContainer(
                new AggregateCatalog(AssemblySource.Instance.Select(x => new AssemblyCatalog(x)))                
                );


protected override IEnumerable<Assembly> SelectAssemblies()
{
    string _modulePath = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "Modules");
    var files = Directory.GetFiles(_modulePath, "*.dll", SearchOption.AllDirectories);

    List<Assembly> assemblies = new List<Assembly>();
    assemblies.Add(Assembly.GetExecutingAssembly());
    foreach (var file in files)
    {
        assemblies.Add(Assembly.LoadFrom(file));
    }
    return assemblies;
}

1 个答案:

答案 0 :(得分:2)

由于您使用的是AggregateCatalog,请检查以确保您没有为包含正在执行的程序集的位置添加AssemblyCatalog和DirectoryCatalog。

例如,以下代码避免了两次处理同一个程序集。

var catalog = new AggregateCatalog();
var locations = new List<string>();
foreach (var loc in GetPluginDirectories())
    if (!locations.Contains(loc))
    {
        catalog.Catalogs.Add(new DirectoryCatalog(loc));
        locations.Add(loc);
    }

var asm = Assembly.GetExecutingAssembly();
if (!locations.Contains(Path.GetDirectoryName(asm.Location)))
    catalog.Catalogs.Add(new AssemblyCatalog(asm));
相关问题