Kishore Kumar
Kishore Kumar

Reputation: 12874

ImportMany of MEF loading Contracts twice

I have two classes which Exports IScreen, but when I import the same using

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

The Modules contain four instance of IScreen, but I have Exported only two.

This is Container

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;
}

Upvotes: 1

Views: 667

Answers (1)

John Holliday
John Holliday

Reputation: 1308

Since you are using an AggregateCatalog, check to be sure you are not adding both an AssemblyCatalog and a DirectoryCatalog for the location containing the executing assembly.

For example, the following code avoids processing the same assembly twice.

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));

Upvotes: 2

Related Questions