How to use the MEF IsMultiple property

Background: I'm trying to use MEF to import two assemblies that implement IFoo. For this, it’s not surprising that I use [ImportMany] to import everything, giving me IEnumerable>. My consumer logic then determines which of the imported assemblies to use based on the MetaData Bar.

Each exporter is decorated with the ExportMetadata attribute. This works great when I have:

[Export(typeof(IFoo))]
[ExportMetadata("Bar", "Hello")]
public class Hello : IFoo
{...}

[Export(typeof(IFoo))]
[ExportMetadata("Bar", "World")]
public class World: IFoo
{...}

That is, my IEnumerable has two IFoos.

I want to define one of them by default, so if there is no need for "Hello" or "World", I will look for one with "Default" as my Bar metadata. I tried to do this using the IsMultiple property as follows:

[Export(typeof(IFoo))]
[ExportMetadata("Bar", "Hello", IsMultiple = true)]
[ExportMetadata("Bar", "Default", IsMultiple = true)]
public class Hello : IFoo
{...}

: IsMultiple , Hello IEnumerable.

: MEF / ?

!

+3
1

, , " ", 'this'.

class Hello: IFoo
{
    [Export, ExportMetadata(...)]
    public IFoo Bar { get { return this; } }

    [Export, ExportMetadata(...)]
    public IFoo Default { get { return this; } }
}
+3

All Articles