Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Service Locator: Get all exports

I'm using MEF and I have two exports having the same contract type but with different contract name

Eg:

[Export("TypeA", typeof(MyPlugin))]
[Export("TypeB", typeof(MyPlugin))]

I could retrieve each exports using its respective contract name:

ServiceLocator.GetExportedValues<MyPlugin>("TypeA");

But now I wish to retrieve all instances implementing MyPlugin. is there any way I could do it?

I've tried using the following code:

ServiceLocator.GetExportedValues<MyPlugin>();

But it did not work. Apparently it is used to retrieve only implementations with no specific contract name.

Any opinion?

like image 780
user1928346 Avatar asked Dec 08 '13 09:12

user1928346


1 Answers

I would simply add a nameless export alongside every named export if you want it to be resolvable both ways. For example

// named and nameless
[Export("TypeA", typeof(MyPlugin))]
[Export(typeof(MyPlugin))]

// named nameless, again
[Export("TypeB", typeof(MyPlugin))]
[Export(typeof(MyPlugin))]

class MyPlugin { }


[TestMethod]
public void mef()
{
    var catalog = new AssemblyCatalog(this.GetType().Assembly);
    var container = new CompositionContainer(catalog);

    Assert.AreEqual(2, container.GetExportedValues<MyPlugin>().Count());
}
like image 101
default.kramer Avatar answered Nov 02 '22 11:11

default.kramer