MEF GetExports<T, TMetaDataView> returning nothing with AllowMultiple = True

自闭症网瘾萝莉.ら 提交于 2019-12-03 08:34:06

It is known that MEF has some problems when dealing with AllowMultiple = true. For a complete explanation you could for instance look here, anyway it derives from the fact that the metadata are saved in a Dictionary where the values are arrays when AllowMultiple is true, and such a thing can't be mapped on your IMyInterfaceInfo.

This is the workaround I use. First of all your attribute should derive from Attribute, not from ExportAttribute:

[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public class ExportMyInterfaceAttribute : Attribute, IMyInterfaceInfo
{
    public ExportMyInterfaceAttribute(Type someProperty1, double someProperty2, string someProperty3)

    {
        SomeProperty1 = someProperty1;
        SomeProperty2 = someProperty2;
        SomeProperty3 = someProperty3;
    }

    public Type SomeProperty1 { get; set; }
    public double SomeProperty2 { get; set; }
    public string SomeProperty3 { get; set; }
}

This means that the exported class should have 3 attributes, a standard export and your custom attributes:

[Export(typeof(IMyInterface))]
[ExportMyInterface(typeof(string), 0.1, "whoo data!")]
[ExportMyInterface(typeof(int), 0.4, "asdfasdf!!")]
public class DecoratedClass : IMyInterface

Then you have to define a view for the metadata which will be imported. This has to have a constructor that takes the IDictionary as parameter. Something like this:

public class MyInterfaceInfoView
{
    public IMyInterfaceInfo[] Infos { get; set; }

    public MyInterfaceInfoView(IDictionary<string, object> aDict)
    {
        Type[] p1 = aDict["SomeProperty1"] as Type[];
        double[] p2 = aDict["SomeProperty2"] as double[];
        string[] p3 = aDict["SomeProperty3"] as string[];

        Infos = new ExportMyInterfaceAttribute[p1.Length];
        for (int i = 0; i < Infos.Length; i++)
            Infos[i] = new ExportMyInterfaceAttribute(p1[i], p2[i], p3[i]);
    }
}

Now you should be able to successfully call

var myExports = CompositionContainer.GetExports<IMyInterface, MyInterfaceInfoView>();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!