3

I am just getting into MEF and was wondering how you could define the order of collection exported with [ImportMany]?

What I mean here is if I had two classes (Class1, Class2) that implement the interface IService and each of the implementations are in two different libraries (although they could be in the same), I want the Class2 instance to be created before the Class1 instance in the IEnumerable collection defined by the ImportMany attribute. So it is like a pipeline of functionality where Class2 calls are made before Class1 calls.

Also, I have an another Class (Class3 which also implements IService) in another library, which I want introduced later on (i.e. some logging utility), how do I make this the 3rd instance in the ImportMany collection?

svick
  • 236,525
  • 50
  • 385
  • 514
JD.
  • 15,171
  • 21
  • 86
  • 159

2 Answers2

4

From a MEF perspective I think you're approaching this problem from the wrong angle. MEF encourages a separation between interface and implementation. To have the consumer dictate the order of the implementations, it forces it to understand the implementation.

The approach taken by Visual Studio is a bit different. It uses the OrderAttribute, usually in combination with the NameAttribute to let the implementors specify an order. The consumer can then sort the implementors of an ImportMany using a combination of names and order without understanding the underlying implementation.

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • Thank you for the reply. Still a bit confused, as far as the client is concerned, he will have a collection of IService[] which I saw as a pipe line of functionality (we still have separation between interface and implementation here). The consumer/client does not dictate the order, it is what is available and the order they are in the IService[] collection. Now if we want a service to be run before another (in the pipeline), how do we do this? Sorry, if I have not understood your answer (as I clearly haven't) – JD. Jun 07 '10 at 15:49
1

You'll could 'Lazy' load them first and then check an order attribute as you add them to a collection.

Or check out this answer which has an example of exacly what you're trying to do.

Community
  • 1
  • 1
Tim
  • 7,746
  • 3
  • 49
  • 83