Search code examples
c#-4.0dependency-injectionmef

Provide different values for same Import using MEF


This question is pertaining to the usage of MEF.

I want to provide different values for the same import in these two scenarios

[Export("A1", typeof(IA))]
[Export("A2", typeof(IA))]
class A : IA
{
  [Import("B")]
  public IB B;
}

[PartCreationPolicy(CreationPolicy.NonShared)]
[Export(typeof(IA))]
class A : IA
{
  [Import]
  public IB B;
}

In both of the two scenarios above, I want to satisfy the import of IB with different values that is when I do this in the first type of export

var a1 = Container.GetExportedValue<IA>("A1");
var a2 = Container.GetExportedValue<IA>("A1");

or this in the second export

var a1 = Container.GetExportedValue<IA>();
var a2 = Container.GetExportedValue<IA>();

I want the two instance of A a1 and a2 to have different values of IB. I don't want to use ImportMany because then I have to decide which one to choose and I want to keep that logic out of class A.

The two scenarios related to these exports are that I want to have a common generic view to work with different types of view models implementing some interface and different instances of a class that provides some service to be configured with different configuration parameters.


Solution

  • Perhaps you are looking for something like this?

    public class AExporter
    {
        [Export("A1", typeof(IA)]
        public IA A1
        {
            get
            {
                 return new A(this.B1);
            }
        }
    
        [Export("A2", typeof(IA)]
        public IA A2
        {
            get
            {
                return new A(this.B2);
            }
        }
    
        [Import("B1", typeof(IB))]
        public IB B1 { private get; set; }
    
        [Import("B2", typeof(IB))]
        public IB B2 { private get; set; }
    
    }
    

    However, MEF isn't really designed for such fine-grained control over the composition. You could try an alternative like Autofac, which integrates well with MEF.