Remove an Export from the part catalog

Jul 9, 2009 at 7:53 AM
Edited Jul 9, 2009 at 7:54 AM

Is there an easy way to remove an Export from the catalog of aviable parts, so it isn't used when composing a part.

The only way that I have found it possible is to implement an ComposablePartCatalog and then override the GetExports.

Is there an easier way to do this?

An example is provided below:

 

 [Export(typeof(IEngine))]
public class V4Engine : IEngine
{
public V4Engine() { Value = "Brum"; }
public string Value { get; set; }
}


[Export(typeof(IEngine))]
public class V12Engine : IEngine
{
public V12Engine() { Value = "WrooommBrummBrumm"; }
public string Value { get; set; }
}

public class MonsterCar
{
[ImportMany(AllowRecomposition = true)]
public IEnumerable<IEngine> Engines { get; set; }
}

class SpecialCatalog : AggregateCatalog
{
public SpecialCatalog()
{
PartsToRemove = new List<ComposablePart>();
}
public List<ComposablePart> PartsToRemove { get; set; }

public override IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> GetExports(ImportDefinition definition)
{
IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> exports = base.GetExports(definition);
foreach (Tuple<ComposablePartDefinition, ExportDefinition> export in exports)
{
foreach (ComposablePart part in PartsToRemove)
{
if (!part.ExportDefinitions.Contains(export.Item2))
yield return export;
}
}
}
}

[TestMethod]
public void CanReDefine_Can_Remove_Import()
{
TypeCatalog typeCatalog = new TypeCatalog(typeof(V4Engine), typeof(V12Engine));
SpecialCatalog catalog = new SpecialCatalog();
catalog.Catalogs.Add(typeCatalog);

CompositionContainer container = new CompositionContainer(catalog);

//Find the first engine to remove
var part = catalog.Parts
.Select(p => p.CreatePart())
.Where(p => p.ExportDefinitions
.Select(ed => ed.ContractName)
.Contains(typeof(IEngine).FullName))
.First();

catalog.PartsToRemove.Add(part);

//Compose it
MonsterCar c = new MonsterCar();
CompositionBatch batch = new CompositionBatch();
batch.AddPart(c);
container.Compose(batch);

//There should only be one engine
Assert.AreEqual(1, c.Engines.Count());
}