Reputation: 4892
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
Upvotes: 1
Views: 820
Reputation: 1009
I know it's been a couple of years, but further investigation helped me find this solution (and I had the exact same problem as the OP): How do you use ExportFactory<T>
And to sum it up:
[ImportMany(typeof(ITask))]
//private IEnumerable<Lazy<ITask, ITaskMetaData>> myTasks;
private IEnumerable<ExportFactory<ITask, ITaskMetaData>> myTasks;
and then:
ITask taskInstance = runner.myTasks.FirstOrDefault(x => x.Metadata.TaskName.Equals(taskDb.TaskObjName)).CreateExport().Value;
where runner is my class with a private constructor that does the MEF magic
Hope this will help someone in the future
Upvotes: 0
Reputation: 49311
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.
Upvotes: 1