MEF open generic problems with 4.5

2019-07-27 08:38发布

问题:

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

回答1:

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.



回答2:

This looks like a bug when using the .NET 4.5 implementation of open generics along with InheritedExport. The MEF team is investigating.

You claim that by adding [InheritedExport(typeof(ITest2<>))] on the ITest2<T> fixed the issue for you however in my attempts to repro this that didn't work either. I only got it to work by adding the explicit Export(typeof(ITest2<>)) directly on the Test2Class.

Can you give some further details about the errors you are receieving? Also are you still using the MEF contrib stuff or did you stop using that with this project?