Importing Multiple InheritedExport Interfaces

Dec 2, 2014 at 10:51 PM
Hello, newby MEF here:

I have 2 interfaces to classlibraries I want to compose with my main application. What i am trying to achieve is a directory of .dlls that I can update/manage for the application as a whole.

InheritedExport]
public interface IObject1
{
  method1();
  method2();
}

InheritedExport]
public interface IObject2
{
  method3();
  method4();
}

Now in the main application thread, I get an error duplicate 'Import' attributes. I want to use both objects in my main application, I just don't know how to import them properly.
#region Imports section

        [Import(typeof(Object1), AllowRecomposition = true)]
        [Import(typeof(Object2), AllowRecomposition = true)]

        private Object1 _obj1;
        private Object2  _obj2;
   #endregion

 private void Compose()
        {
            dirCatalog = new DirectoryCatalog(@"D:\Folder");
            AssemblyCatalog assemblyCat = new AssemblyCatalog(System.Reflection.Assembly.GetExecutingAssembly());
            AggregateCatalog catalog = new AggregateCatalog(assemblyCat, dirCatalog);
            CompositionContainer container = new CompositionContainer(catalog);
            container.ComposeParts(this);
        }
Coordinator
Dec 16, 2014 at 10:50 PM

jpatrick62,

you need to apply the import attributes over each property as below. Two imports on the same property will not work as the composition engine will not know which import it should use to satisfy a property. If there are multiple Exports that can satisfy an import use the ImportMany attribute.

        [Import(typeof(Object1), AllowRecomposition = true)]
        private Object1 _obj1;
 
        [Import(typeof(Object2), AllowRecomposition = true)]
        private Object2  _obj2;

cheers

-alok