Setting up Policies for Extensible Parts in MEF

By | September 7, 2011

Part Lifetime is one of the most important hindrances that we face while working with MEF. It is very important to understand how the parts are going to be shared between plugins such that having been so much open ended, 3rd party plugins remain separated to the objects that you do not want to be shared outside.  In this post I am going to define how Part creation policies can be setup on an object to ensure how the object needs to behave in the CompositionContainer.

It is true that MEF is very well constructed and everything could be defined just in forms of an attribute, Part lifetime can also be set using a special attribute called PartCreationPolicy.

[PartCreationPolicy(CreationPolicy.NonShared)]
public Action MyActionDelegate { get; set; }

This means the container will secure the object Action to be shared to any other import in the container either directly or indirectly. There are three states of CreationPolicy :

  • Shared : This means the object will be shared in the container for any other import statement. This is the default settings for any Export and content can associate with any other component.
  • Non-Shared : This means the object will not be shared either directly or indirectly. This is used only when you do not want to share your object and risk being exposed to 3rd party libraries.
  • Any : This settings will choose either shared or non-shared value.

Even with Imports you can constraint it using RequiredCreationPolicy.

[Import(RequiredCreationPolicy = CreationPolicy.Any)]
public Action MyActionDelegate { get; set; }

Here the CreationPolicy is constraint by the CreationPolicy Attribute. The behavior of creation policy can be defined as :

Part.Any Part.Shared Part.NonShared
Import.Any Shared Shared Non Shared
Import.Shared Shared Shared No Match
Import.NonShared Non Shared No Match Non Shared

Read more about it from the links :

Managed Extensibility Framework – A Look

Steps to write a plugin based application with MEF

Thank you for reading.