Use of ImportConstructor to inject Constructor code in MEF

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
{

[ImportingConstructor]
public ExportContainer([Import(AllowDefault=true)]Action specialDelegate)
{
this.MyActionDelegate = specialDelegate;
}

public string ExportName { get; set; }

[Export]
[ExportMetadata("Name", "Plugin from Plugin1")]
public string GetName()
{
this.ExportName = "Plugin from Plugin1";

if (this.MyActionDelegate != null)
this.MyActionDelegate(this.ExportName);

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.

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