Private vs. Public mystery

Sep 22, 2008 at 9:13 PM
I've noticed that in samples some [Import] declarations are declared private, and some public. In my own test, if I declare an import as a private, it simply doesn't work - and honestly, I don't understand HOW private import can be satisfied by the service.
So what are the rules for public vs. private imports?
Sep 22, 2008 at 9:27 PM
Hello saldoukhov,

to allow private imports/exports to be discovered by MEF, you have to use the assembly-level AllowNonPublicComposition attribute. For example, the Meftris sample places it in the AssemblyAttributes.cs file. This attribute prevents part writers from unintentionally exposing private/internal members.

Hope that helps,
Jad
Oct 6, 2008 at 4:37 AM
Be aware that you will take a significant performance hit if you use private members for composition.  I just recently went through an exercise of improving performance (using dotTrace) in a WEB application that was using JSON.NET to serialize a private nested class.  Hotspots came up with the demand checks (due to these classes being private), which have to do expensive stack walks.  By making the classes public (still nested), the demand checks disappeared.

I would expect MEF is subject to the same CAS performance issues.  For one time build-up, not an issue, but for objects that are composed frequently, choose your private members wisely.

Cheers,

Stuart