Removing Parts from a CompositionContainer Using a CompositionBatch Object

I have a MEF-based solution that has several exported interface implementations.

What I want to do is to have a switch that deletes ALL the current parts associated with the interface and replaces them with only one implementation instead. I am trying to do this with a CompositionBatch object, but it does not seem to work. Here is an example of what I am doing:

 [Export(typeof(IFoo)] public class Foo1 : IFoo { } [Export(typeof(IFoo)] public class Foo2 : IFoo { } 

Then I have a container:

 var container = new CompositionContainer(....); 

which will now contain parts representing Foo1 and Foo2 . What I want to do replaces them with another IFoo implementation. This is what I am trying, and I thought it would work:

 var partsToRemove = from part in container.Catalog.Parts from exDef in part.ExportDefinitions where exDef.ContractName == AttributedModelServices.GetContractName(typeof(IFoo)) select part.CreatePart(); var batch = new CompositionBatch(null, partsToRemove); batch.AddPart(new Foo3()); container.Compose(batch); 

I expect container.Catalog.Parts change to reflect my changes, but it is not. It remains the same as when creating the container.

What am I missing? Is this even the right approach? I read the article by Glenn Block CodeBetter about using ExportProviders , but he mentions that he will write part 2 in which he will consider the implementation of the ExportProvider filter (which may be closer to what I need to do).

+3
source share
2 answers

So, CompositionBatch is the addition and removal of explicit instances of objects and is not related to the catalog, namely the addition of a set of definitions (for example, types, if necessary), which will then be subsequently constructed into object instances in CatalogExportProvider. To do what you want, you will need to actually filter the directory before passing it to the container to exclude the types you need. (See http://mef.codeplex.com/wikipage?title=Filtering%20Catalogs for an example filtering directory).

Then, if you want to add an explicit instance of Foo, you can use CompositionBatch to do this.

+5
source

Tim, do you expect to do this dynamically at runtime after creating the container, i.e. after the container has already created some parts? Or are you trying to just apply a filter during startup?

+1
source

Source: https://habr.com/ru/post/1346498/


All Articles