Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define the order with ImportMany attribute?

Tags:

.net

mef

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?

like image 431
JD. Avatar asked Dec 14 '25 09:12

JD.


2 Answers

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.

like image 177
JaredPar Avatar answered Dec 17 '25 21:12

JaredPar


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.

like image 37
Tim Avatar answered Dec 17 '25 22:12

Tim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!