问题
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?
回答1:
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.
回答2:
Have a look at AttributedModelServices.ComposeExportedValue. You would use it like this:
m_container.ComposeExportedValue<IFoo>(new IFooImpl());
回答3:
The latest preview version of MEF has a class called RegistrationBuilder which you can use to configure your MEF parts via code. You can get the preview version from the MEF CodePlex site.
Here's a blog post with an overview of the new features.
来源:https://stackoverflow.com/questions/3493640/mef-how-to-manually-configure-export-for-a-contract-implementation