This project has moved and is read-only. For the latest updates, please go here.

MEF2: How do I get my hands onto an ExportFactory?

Dec 6, 2011 at 10:21 PM

I need to create an object that "inherits" from Context in a factory method (on my central application object).

For that - due to the lifetime control possible - I want / need to get an instance of ExportFactory<TContext>. How can I do that?


        public TContext GetContext<TContext>() where TContext : Context {
            ExportFactory<TContext> factory = CompositionContainer.GetExportedValue<ExportFactory<TContext>>();
            var ltc = factory.CreateExport();
            // need to put the ltc into the Context so it can be properly disposed via the ltc dispose method.
            TContext context = ltc.Value;
            return context;


sadly blows with the usual cardinality export ;)

No exports were found that match the constraint:  ContractName System.ComponentModel.Composition.ExportFactory(CodeCore.Tests.ApplicationModel.ApplicationTests+ContextAA) RequiredTypeIdentity System.ComponentModel.Composition.ExportFactory(CodeCore.Tests.ApplicationModel.ApplicationTests+ContextAA)

Obviously I can not just get an Export onto ExportFactory... The only visible constructor needs a function to a Tuple that looks like it is internal.

Dec 9, 2011 at 12:45 AM
Hi there - here's one option:
class ExportFactoryImporter<T>
   public ExportFactory<T> ExportFactory { get; set; }


 public TContext GetContext() where TContext : Context {
    var importer = new ExportFactoryImporter();
    ExportFactory factory = importer.ExportFactory;

It is usually better to avoid this kind of service-location altogether when possible though. Generic parts might give you some options for making the export factory a first-class import of another part.