Search code examples
c#genericsmef

MEF Generic Imports


I have the following example code using MEF:

public interface IFoo<T> 
{}

public class Foo<T> : IFoo<T> 
{}

[Export(typeof(IFoo<String>))]
public class Foo : Foo<String> 
{}

public class Bar<T>
{
   [Import]
   private readonly IFoo<T> foo;
}

static void Main()
{
   var catalog = new AggregateCatalog();
   catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
   var container = new CompositionContainer(catalog);
   container.ComposeParts();

   var bar = new Bar<String>();
   //bar.foo would be null
}

This doesn't seem to work - the foo field is null. Is this because its type isn't seen by MEF as IFoo<String> ?


Solution

  • foo is null because you are creating the instance yourself. You need to have the container create the instance.

    Additionally, you will want to check out the GenericCatalog if you plan on working importing/exporting generics.