This is a mirror of official site: http://jasper-net.blogspot.com/

Use of ImportConstructor to inject Constructor code in MEF

| Wednesday, September 7, 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
{

   [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);

Read more: Daily .Net Tips
QR: https://chart.googleapis.com/chart?chs=80x80&cht=qr&choe=UTF-8&chl=http://dailydotnettips.com/2011/09/06/importconstructor-to-inject-constructor-mef/

Posted via email from Jasper-net

0 comments: