Search code examples
.netmef.net-4.5

MEF open generic problems with 4.5


We were using MEF Contrib open generics support like this:

[InheritedExport]
interface ITest2<T>
{
    void Execute();
}

class TestClass2<T> : ITest2<T>
{
    public void Execute()
    {
        Console.WriteLine();
    }
}

class Program
{
    static void Main(string[] args)
    {
        var catalog = new AssemblyCatalog(typeof(Program).Assembly);
        var container = new CompositionContainer(catalog);
        var test2 = container.GetExportedValues<ITest2<string>>();
    }
}

However, since the installation of .NET Framework 4.5, this code no longer works. Not only does it no longer work after building against .NET 4.5, or .NET 4.0, but it also breaks existing compiled applications.

It appears that one has to either use an explicit [Export(typeof(ITest2<>))] attribute on TestClass2, or to change the definition:

[InheritedExport(typeof(ITest2<>))]
interface ITest2<T>
{
    void Execute();
}

Does anyone know why this has changed? Curiously, MEF's open generics support (in 4.5) also fails with a non-typed [InheritedExport] attribute on an open generic interface.

I would have thought that the default behaviour for [InheritedExport] on an open generic interface would be the same as [InheritedExport(typeof(ITest2<>))].

Thanks, Steve


Solution

  • This is a bug in the .Net 4.5 MEF implementation of Open Generics support. It will be fixed in the next release of .Net framework.

    There are a couple of work arounds none of them ideal.

    1. Make the interface an abstract base class
    2. Remove the InheritedExport from the interface and explicitly mark the derived classes with the Export Attribute.

    I hope this helps.