Use of ImportConstructor to inject Constructor code in MEF

By | September 6, 2011

Just like what I have talked for so long in my blog entries about Import, ImportConstructor is another attribute that you can annotate only for a constructor. Sometimes it is needed to have some kind of Dependency that needs to be injected while constructing the object.  In case of a normal Import, the Property is set using Default Constructor, and will be Composed when it is being used, but what if, you need certain kind of rules while creating the object?

ImportConstructor allows you to annotate a constructor in such a way that the Composer will call it when it creates an object of that class.

 Lets see the code how it works :

public class ExportContainer
public ExportContainer([Import(AllowDefault=true)]Action specialDelegate)
this.MyActionDelegate = specialDelegate;
public string ExportName { get; set; }
[ExportMetadata("Name", "Plugin from Plugin1")]
public string GetName()
this.ExportName = "Plugin from Plugin1";
if (this.MyActionDelegate != null)
return this.ExportName;
public Action MyActionDelegate { get; set; }

The class here specifies a ImportConstructor which requires a parameter of delegatate Action. You are also allowed to pass an Import attribute on parameters passed in a method, hence I have used just that in case of constructing the object of ExportContainer. The AllowDefault = true for an import will make the object to its default value (null for objects) when it is unavailable in the Container thus relaxing the runtime exception to occur.

You can now create a CompositionContainer to compose its parts and you will see the actual constructor is appropriately called.

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.