Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing many instances using MEF

Tags:

c#

mef

I'm exporting some classes implementing the IFoo interface like this

public interface IFoo { }

[Export("A", typeof(IFoo))]
public class Foo1 : IFoo { }

[Export("B", typeof(IFoo))]
public class Foo2 : IFoo { }

When I try to import one of them using

 containter.GetExportedValue<IFoo>("A"); 

it works well but when I try to import all of them like this

[ImportMany]
IFoo[] foos;

it doesn't work.

Can someone tell me how to solve this?

like image 965
Michelle Avatar asked Mar 09 '12 17:03

Michelle


2 Answers

To have it both ways, declare 2 exports:

public interface IFoo { }

[Export(typeof(IFoo))]
[Export("A", typeof(IFoo))]
public class Foo1 : IFoo { }

[Export(typeof(IFoo))]
[Export("B", typeof(IFoo))]
public class Foo2 : IFoo { }

Then it should work (i did a test sample and got it to work).

HTH,

Bab.

like image 199
Louis Kottmann Avatar answered Oct 26 '22 00:10

Louis Kottmann


Remove the contract names on your exports.

[Export("A", typeof(IFoo))]

To

[Export(typeof(IFoo))]

In the first scenario you are exporting a contract that matches the name "A" and the type IFoo, while in your import many you are importing everything that matches a contract of type IFoo (no contract name), so the exports with contract names aren't considered.

As baboon mentioned, you can have it both ways. You should consider if you need both in your application, if it is not the case, I would stick with only one way to keep things as simple as possible, otherwise I suggest using his approach.

like image 22
Gilles Avatar answered Oct 26 '22 00:10

Gilles