Setting up Policies for Extensible Parts in MEF

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.

Abhishek Sur

Abhishek Sur is a Microsoft MVP since year 2011. He is an architect in the .NET platform. He has profound theoretical insight and years of hands on experience in different .NET products and languages. He leads the Microsoft User Group in Kolkata named KolkataGeeks, and regularly organizes events and seminars in various places for spreading .NET awareness. He is associated with the Microsoft Insider list on WPF and C#, and is in constant touch with product group teams. He blogs at http://www.abhisheksur.com His Book : Visual Studio 2012 and .NET 4.5 Expert Development Cookbook. Follow Abhishek at Twitter : @abhi2434