tags:

views:

28

answers:

2

Hi, I have a MEF's CompositionContainer, a contract (say IFoo) and a module (Prism module but it doesn't matter much here, just some component). I want in my module to register the contract's implementation (FooImpl).

If it's Unity I'd do like this:

unity.RegisterType<IFoo, FooImpl>().

That's all. With MEF I've puzzled. I have to mark my implementation with ExportAttribute, but that lead to it'll be exported automatically. I want to manage this by myself. Take a look at the code:

class MyModule: IModule {
  private CompositionContainer m_container;
  public MyModule(CompositionContainer container) {
    m_container = container;
  }
  public void Initialize() {
    ??? I want something like m_container.CreateExport<IFoo, FooImpl>()
  }
}

public interface IFoo {}
public class FooImpl : IFoo {
    //[ImportingConstructor]
    public FooImpl(ISomeService svc) {}
}

In Initialize I want manualy export FooImpl as IFoo contract not relying on ExportAttribute on FooImpl class. I understand that I just can create an instance FooImpl (in MyModule.Initialize above), but FooImpl has constructor dependencies on other component/services and I want they to be resolved on creation.

So probably I should ask: how to manually add export having a CompositionContainer instance and a contract? And then mark this export somehow as it has ImportingConstructorAttribute?

A: 

That's not how MEF works by default. However, you can create your own ExportProvider implementation which does this, and pass it to the CompositionContainer constructor.

The MEF contrib project has a few examples of export provider implementations. The Fluent Definition Provider is probably the closest to what you describe. There is also an export provider which provides integration with unity.

Wim Coenen
Thanks, I'll have a look. But I'd like to do this with already existing CompositionContainer.
Shrike
A: 

Have a look at AttributedModelServices.ComposeExportedValue. You would use it like this:

m_container.ComposeExportedValue<IFoo>(new IFooImpl());
Daniel Plaisted
Here I'm loosing constructor dependencies substitution.
Shrike