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
In that thread, Andrew was asking why the following does not work?
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.
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…
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….
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.
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.