Multiple plugin instance loading with MEF
Posted
by Dave
on Stack Overflow
See other posts from Stack Overflow
or by Dave
Published on 2010-06-02T21:00:35Z
Indexed on
2010/06/02
21:04 UTC
Read the original article
Hit count: 213
In my last application, using MEF to load plugins went just fine, but now I'm running into a new issue. I have a solution for it that I explain at the end of this question, but I'm looking for other ways to do it.
Let's say I have an interface called ApplianceInterface. I also have two plugins that inherit from ApplianceInterface, let's call them Blender and Processor. Now, I would like to have multiple Blenders and Processors in my application, but I am not sure how to instantiate them properly.
Before, I would simply use the ImportMany
attribute and upon calling ComposeParts, my application would load Blender and Processor. For example:
[ImportMany(typeof(ApplianceInterface))]
private IEnumerable<ApplianceInterface> Appliances { get; set; }
and my Blender and Processor plugins would be attributed like this:
[PartCreationPolicy(CreationPolicy.NonShared)]
[Export(typeof(MyInterface)]
public class Blender : ApplianceInterface
{
...
}
but what this ends up doing for me is populating Appliances with one Blender and one Processor. I need to be able to create an arbitrary number of Blender and Processor objects.
Now, from the documentation I understand that [PartCreationPolicy(CreationPolicy.NonShared)]
is what allows MEF to create a new instance each time, but is there a similar "magical" way to create a specific number of instances of something using MEF? Up until now, I've relied on [Import]
and [ImportMany]
to resolve the assemblies.
Is my only option to use a global container, and then resolve the export manually using GetExportedValue<>? I have tried GetExportedValue<> and that implementation does work fine for me, but I was just curious if there is a better, more accepted way to do it.
© Stack Overflow or respective owner