How to add instance of the class which satisfies import to CompositionContainer

StackOverflow https://stackoverflow.com/questions/22517090

  •  17-06-2023
  •  | 
  •  

Question

I am facing the following problem:

var catalog = new AggregateCatalog();
catalog.Catalogs.Add(new AssemblyCatalog(typeof(Type1).Assembly));
catalog.Catalogs.Add(new AssemblyCatalog(typeof(Type2).Assembly));

using (CompositionContainer container = new CompositionContainer(catalog))
{
}

I need one more export:

Export[(typeof(Type3))]

The thing is that I can't include an assembly with the class which has this Export attribute. I want to tell the container that:

var myObject = new Type4();

myObject (the instance of Type4) should be exported each time the Import[(typeof(Type3))] is needed. Besides I can't mark Type4 with Export[(typeof(Type3))] and also I want the instance of the class to be used by MEF (so marking this class with Export attribute doesn't work, because I am changing myObject before I pass it to MEF and I want it to be used to satisfy Import).

Then when I try to do:

container.SatisfyImportsOnce(importer);

I expect that MEF will get all the objects from the assemblies in catalog, and for the missing Type3 it will use myObject. This should be the value when I do:

container.GetExportedValue<Type3>();

I spent one day trying different approaches: custom ExporterProvider and some sort of inheritance from Type4 to mark it with proper Export attribute but I can't get it working as I want.

I would be very grateful for help.

Thank you!

Was it helpful?

Solution

Ok, already found an answer.

  1. First problem was that I added 2 the same AssemblyCatalogs to AggregateCatalog - don't do that.

  2. The solution is to use CompositionBatch:

    var catalog = new AggregateCatalog();
    catalog.Catalogs.Add(new AssemblyCatalog(typeof(Type1).Assembly));
    catalog.Catalogs.Add(new AssemblyCatalog(typeof(Type2).Assembly));
    var myObject = new Type4();
    
    using (CompositionContainer container = new CompositionContainer(catalog))
    {
      var batch = new CompositionBatch();
      Export ex = CreateExport<Type3>(myObject);  //Custom implementation
      batch.AddExport(ex);      
      container.Compose(batch);
      var val = container.GetExportedValue<Type3>();  //value == myObject
    }
    

Thank you!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top