Registering types and instantiation

Aug 10, 2011 at 8:58 AM

Hello,

I am currently investigating MEF, and have a few questions:

1) to me, it seems that the [Export] attribute registers a type, not an instance (at least, I hope not all types with [Export] are instantiated when added to the catalog). Is that correct?

2) I can use the ComposeExportedValue to register a specific instance to a CompositionContainer, but how can I register a specific type without instantiating it? I want MEF to instantiate the type on-demand, but I cannot use the [Export] attribute for some reasons.

 

Thanks in advance!

Aug 10, 2011 at 12:42 PM
Edited Aug 10, 2011 at 12:43 PM

1) Yes, an [Export] attribute registers a type. However, the default behavior in MEF is to reuse instances, unless you put a part creation policy on the export and/or import which says otherwise.

2) Mark Seemann demonstrated a trick which you can use to register existing types without MEF attributes: http://blog.ploeh.dk/2011/03/14/ResolvingClosedTypesWithMEF.aspx.

Alternatively, you can use the latest MEF 2 Preview, which adds a Convention Model: http://blogs.msdn.com/b/hammett/archive/2011/03/08/mef-s-convention-model.aspx

Aug 10, 2011 at 4:43 PM

Thanks for your reply, but it's not fully what I meant (I was probably unclear in my first question).

1) I meant that it registers a type (say PersonClass) instead of an instance. It will create the first instance when it is first requested, right? After then, it will keep returning the same instance (singleton behavior).

2) The trick he shows still requires me to write code, but I need to register types that I am not aware of on forehand (via reflection, the author of the 3rd party library should not be aware of the usage of MEF at all).

So, in general, I have found a way to register instances via code, but I cannot find a way to register a type that should be instantiated in the future on the first import or resolve action.

Aug 11, 2011 at 10:27 AM
Edited Aug 11, 2011 at 10:28 AM

1) I meant that it registers a type (say PersonClass) instead of an instance. It will create the first instance when it is first requested, right? After then, it will keep returning the same instance (singleton behavior).

Yes.

2) The trick he shows still requires me to write code, but I need to register types that I am not aware of on forehand (via reflection, the author of the 3rd party library should not be aware of the usage of MEF at all).

Then use the Convention Model in the latest MEF 2 Preview which I already mentioned. Or use the convention model provided by MefContrib. Or implement your own ComposablePartCatalog.

Aug 13, 2011 at 10:38 AM

Thank you very much. I think I'll writemy own ComposablePartCatalog in that case.