MEF not supporting open generic types

If you are trying to use MEF with open generic types like:

[Export(typeof(IRepository<>))]
public class itial; padding: 0px; margin: 0px; border: 0px initial initial;">Repository<T> : IRepository<al; background-color: transparent; color: black; background-position: initial initial; background-repeat: initial initial; padding: 0px; margin: 0px; border: 0px initial initial;">T>
   
where T : class
{

With an import of

[Import(typeof(IRepository<>))]
private IRepository<Contact> repository;

You’ll come stuck, as the current implementation MEF does not support Open Generic Types.

For more information take a look at Glenn Block article Why doesn’t MEF support open-generics for exports? Because MEF is not type based

Also there is Open-generic support in the MEF Contrib, which can be found on codeplex.

The reasoning is this, MEF parts relate on contracts which are strings, not types. To illustrate, see the code below.

namespace Orders {

  public interface IOrderRepository {}

  [Export(typeof(IOrderRespository))]

  public class OrderRepository : IOrderRepository {

  }

}

Although I have passed typeof(IOrderRepsitory) to the export, that is just a convenience that gets converted to a contract name of “Orders.IOrderRepository”. The same applies to the importer…

[Export]

public class OrderService(

  [Import]

  public IOrderRepository Repository {gets;set;} 

)

The import on IOrderRepository also gets converted to a contract name of “Orders.IOrderRepository”. This way the container is able to satisfy the import as the 2 contracts match. In the same way we support closed generics, so….

public interface IRepository<T> {}

namespace Orders {

  [Export(typeof(IRepository<Order>))]

  public class OrderRepository : IRepository<Order> {

  }

}

[Export]

public class OrderService(

  [Import]

  public IRepository<Order> Repository {gets;set;} 

)

Will work because the OrderRepository is exporting the contractname “Orders.IRepository<Order>” and the OrderService is importing the same contract.

However, this is what it looks like if we try the same with open generics.

public interface IRepository<T> {}

namespace Utils {

  [Export(typeof(IRepository<>))]

  public class Repository : IRepository<T> {

  }

}

[Export]

public class OrderService(

  [Import]

  public IRepository<Order> Repository {gets;set;} 

Now the contract names will be different. The exporter will have a contract of  “Utils.IRepository<>” and the importer will have a contract of “Utils.IRepository<Order>”.

It is a simple match up, that breaks down in the open-generics case. This is because fundamentally, MEF is not matching on type.

Original article form codeplex