Default PartCreationPolicy

Nov 24, 2011 at 8:32 AM

Hi Guys,

I really like MEF, but where I am working now we are using MEF as a dependency injection framework because it's easy to mark up your exports and because we do not have a single file where we register our implementations.

But I hate the fact that I have to go through each and every export and mark it with PartCreationPolicy attribute, because in a normal scenario you want your dependencies to be non shared since they hold instance variables.

Is there any way I can change the default behaviour of CreationPolicy.Shared when none has been defined?

Having to specify on the imports that I want a NonShared or on the exports that I want a NonShared seems counter intuitive to me.

The other way around would be best in my scenario.

I understand that if you are using mef to export methods, to get rid of static methods on static classses, Shared is what you want.

Would it be possible to add a configuration on the CompositionContainer or somewhere else where I as a user can configure the default CreationPolicy.

For backwards compatibility you can have that configuration to be the same standard as now, but it would really be a huge benefit if you can configure your container's default creationpolicy, since not everyone's needs are the same.

Thanks

Bjørn Smith

Nov 25, 2011 at 2:21 PM

Hi Bjørn,

In MEF 2, RegistrationBuilder fills this need:

    var builder = new RegistrationBuilder();

    builder.ForTypesMatching(t => true).SetCreationPolicy(CreationPolicy.NonShared);

    var catalog = new AssemblyCatalog(myAssembly, builder);

All of the catalog types in MEF 2 support RegistrationBuilder, AssemblyCatalog here is just an example.

The behavior of RegistrationBuilder is overridden by the application of attributes to the part types themselves, so CreationPolicy.Shared can be applied as necessary.

This will change two other things:

  • [ImportingContstructor] becomes optional - the constructor with the longest parameter list will be used on all parts
  • [ImportMany] becomes optional on collection-valued imports

Hope this helps.

Nick