Aug 11, 2010 at 6:37 AM
Edited Aug 11, 2010 at 6:41 AM
To get this, I suggest you fire up a small test project with the sole purpose of working out these things. Assert expected behavior in isolation. I do this, and it does help me understand where MEF does what (besides reading the source).
Maybe this will clear up the export/import confusion a bit.
The basic MEF objects are Catalogs, Containers and Parts. Each part can have several export or import definitions. However, only exports can be created within the container.
When you ask the container for a part you do this by specifying a contract name (this is just a string that defaults to something which looks like a type name). You'll always get back an export or exception (the many situation returns
an non-empty collection or an empty collection) but either way never null (unless you change your import definition to allow the default value). But before you gain access to the created export, the import definitions of
the part are all satisfied. If this is not possible the part is rejected (this is called stable composition). All this occurs within the container.
Some times you don't create the part through the container, and when that happens you need to tell the container to satisfy the imports yourself.
var batch = new CompositionBatch();
That snippet actually does two things. It searches the part for import definitions and ensures that they are satisfied but also if the part itself is an export it will put that instance into the container (it now being available for satisfying other imports).
If your part is an export and you compose it you also add it to the container. Normally you add parts through catalogs, but it can be done this way as well.
Make sure you are using the namespace System.ComponentModel.Composition and try the extension method SatisfyImportsOnce provided by the AttributedModelServices.
If you have a type (no export attribute) with imports and you want them to be satisfied that's the call you wanna make. Pass an instance of some type which has import definitions and see that it will either throw an exception or have non null values
for those imports.