tags:

views:

39

answers:

1

I am sure this should be easy, perhaps I am missing something obvious. I have a bunch of classes that implement the IClass interface. At runtime I want to use the MEF DirectoryCatalog to retrieve references all those classes implementing that IClass interface. So, at this point I have some kind of pool of classes that can be instantiated.

Now, from this point on I want to be able to instantiate one or many of these classes based upon whatever business logic is executing at the time. So I have managed to get the DirectoryCatalog working fine. I have also managed to implement an ImportMany so that a collection of those classes implementing the IClass interface exist.

This would be fine, but I don't want to simply have a collection of all classes and I may want to be able to instantiate more than one version of that class at any time. I started looking at using Lazy, but I assume this would simply assist with when the class is instantiated, not how many.

Again, I can't help but think I am missing something obvious. Any assistance would be most grateful.

Thanks

+1  A: 

I want to be able to instantiate one or many of these classes based upon whatever business logic is executing at the time.

MEF doesn't understand your business logic, so it's not unreasonable that it doesn't provide a mechanism to only instantiate classes based on it. The idea is that any object which exposes an interface to MEF can be used in that role by the application, including any created by third parties.

Instead, expose factories which have an interface that allows them to decide whether or not to instantiate an object based on whatever parameters the decision is made on. If only one object is required from all the possible providers, have them expose some metadata which will enable the client to decide the best factory to use.

Pete Kirkham
OK, so I create a Factory that the main application uses and this factory can create instances by using the AssemblyQualifiedName. However, I still need to be able to dynamically load the referenced assemblies that contain the concrete classes that implement IClass. Do I therefore just do a lazy ImportMany on the main class to set this up and then use the factory to actually instantiate the classes? This would therefore mean the ImportMany isn't ever used except to setup this link? Thanks
Jon Archway
@Jon Archway The ImportMany would import many factories, you then use them to create the appropriate IClass instances. If you want to allow for dynamic loading failures, use lazy and create a list of factories from the lazy values. There's not normally any need to use qualified names within the factories - just create an instance of the IClass object.
Pete Kirkham