Search code examples
mef

How to populate fields with MEF on instances when they are created


The example in the docs has a calculator field being filled that exists on the same object that is calling

_container.ComposeParts(this);

I'm a little confused about the ComposeParts() method though. I'm guessing that it's not something you're supposed to call in the constructor of all objects that import values, so what is the correct way of getting MEF to fill fields on objects when they get instantiated?


Solution

  • Nope, you don't need to call ComposePart() in every constructor. During composition MEF (at runtime), goes through all the catalogs and tries to match up Imports with valid Exports. This one of the things that is definitely a gotcha- you have to let MEF instantiate your objects, you don't do it yourself (or tell WPF/Silverlight to do it). It cascades through your projects and classes hooking everything up.

    If there are classes that DO have imports but you need to dynamically create instances of those then you COULD use something like this in the constructor- like CompositionInitializer.SatisfyImports().

    But if you are doing this, then I think the recommended practice is to look at a different container, like Unity.