Search code examples
.netmef

Import multiple instances of a class differed by parameter value in MEF


I would like to export from one type two its different instances that differ in parameters that were passed to their constructors.

To be more specific:

interface IA {
 string P { get; }
}

[Export(typeof(IA))]
[ExportMetadata("p", "1")]
[ExportMetadata("p", "2")]
class A : IA {

 [ImportingConstructor]
 public A( string p ) {
  this.P = p;
 }

 public string P { get; set; }
}

I would like, when importing a collection of IA's, get two instances of A that were instantiated with different values of constructor parameter p - one with 1 and other with 2 (I want these parameters to be taken from export metadata).

Is it possible to archieve this in MEF?


Solution

  • Would a property export work for your scenario?

    class A : IA
    {
        public A(string p) { P = p; }
        public string P { get; set; }
    }
    
    class AExports
    {
        [Export(typeof(IA))]
        [ExportMetadata("p", "1")]
        public IA A1
        {
            get { return new A("1"); }
        }
    
        [Export(typeof(IA))]
        [ExportMetadata("p", "2")]
        public IA A2
        {
            get { return new A("2"); }
        }
    }