Why doesn’t MEF support open-generics for exports? Because MEF is not type based.

Update: We’ve posted an extension for doing open generics in MEF contrib. Read about it here: http://codebetter.com/blogs/glenn.block/archive/2009/08/20/open-generic-support-in-mef.aspx

I get this question all the time. Recently it popped it’s head on the forums in this thread (which I referred to in my last post)

In that thread, Andrew was asking why the following does not work?

[Export(typeof(IDomainController<>)), CompositionOptions(CreationPolicy = CreationPolicy.Shared)]

public class DomainController<T> : IDomainController<T>

{

  /* some code here */

  [ImportingConstructor]

  public DomainController(IRepository repository)

  {

 

    _Repository = repository

  }

} 

That is he wants to export a generic IDomainController with the idea the closed generic versions like IDomainController<Customer> could be imported.

He also rightly observed that many of the IoC containers that exist support this functionality including Unity. (I chuckled when I heard that because I was in p&p when we first wrote Unity) However, it is a valid question, why don’t we support it? This is one of those questions that I, Hammett and Nick all asked when we joined the team.  We do support closed generics without a problem, but not open. Why?

As you dig into the details, it quickly becomes clear. The root of the answer is that MEF is not type based, it is contract based. Below are the details from my response…

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(IOrderRepository) 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”. During composition, the container is able to satisfy the import as the 2 contracts match. In the same way we support closed generics, so this code….   

public interface IRepository<T> {}

 

[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 contract name “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.

There are theoretical ways to address it, but they are all very ugly, require a lot of string parsing and really go against the grain of MEF’s core design.

This entry was posted in Generics, MEF. Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • http://meandmycode.com Stephen

    What you are talking about with generics, abstractly I guess is variants, would it not be possible to design the strings to be less ‘dumb’, and support variance? this way you can say.. we didn’t add generics support specifically, we added variant support and mapped generics to that ;).

    But perhaps you are right, this isn’t something that MEF supports, and you certainly need a set of opinions to stand by otherwise you’ll end up with a cluttered mess thats been pulled each way to fit uncertain requirements.

  • http://www.codebetter.com/blogs/glenn.block/ Glenn Block

    Hi Torkel

    Dynamic languages are one instance, though there are others like supporting Xaml etc.

    In terms of limiting, the question is HOW is it limiting for extensibility scenarios. Yes IoC containes support it, but give me scenarios where you absolutely can’t live with out it.

  • http://www.codinginstinct.com Torkel

    The idea to have contracts represented as strings seems to be a big limitation, I understand the reasoning (to be able to support dynamic languages).

  • http://www.codebetter.com/blogs/glenn.block/ Glenn Block

    Hi Rob.

    Actually in our next drop we do allow you to harden contacts to say that the implementer must be of a certain type. We call this feature Typed Imports/Exports. Using Typed I/E you can still use string contracts, but you can add additional constraints on the actual type. The Export and Import attribute get an additional overload to allow specifying Contract Name AND Type. By default if you just specify a type, then we will use the type for contract name as before, and we will also constrain on that type.

    So…

    [Import]
    public ILogger Logger {get;set;}

    will ONLY match loggers that have an actual type of ILogger

    [Import("Logger", typeof(ILogger)])
    public ILogger Logger {get;set;}

    will only match exports of “Logger” that are of type ILogger.

    [Import("Logger", typeof(object)])
    public ILogger Logger {get;set;}

    will match ANY exporter of “Logger” regardless.

    On the exporter side this

    [Export(typeof(ILogger)]
    public class Logger : ILogger {
    }

    will carry the ILogger type info as well as the contract name

    [Export("MyLogger", typeof(ILogger))]
    public class Logger : ILogger {
    }

    will explicitly say that “MyLogger” matches on type ILogger.

  • http://www.bluespire.com.blogs Rob Eisenberg

    When last I looked into the MEF source, I noticed that contract was essentially a string, and that you had a handful of helper methods surrounding it. This alarmed me quite a bit. I meant to talk with you about this at ALT.NET. Here’s the thought. If contract is such a core concept, why does it exist only implicitly as a string? You should really consider creating an IContract interface with several implementations (maybe you had this and I just missed it, but…) You could then come up with a more elegant solution to the above problem. Even if you don’t support open generics at any point, it still might be valuable to make the idea of contract more explicit.