Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating multiple instances of Imported MEF parts

Tags:

c#

.net

mef

Currently my WPF application imports a part like this

[Import(typeof(ILedPanel)]
public ILedPanel Panel { get; set; }

But this gives ma a single intance of the class that implements ILedPanel. What I really want to do is have the ability to create as many instances that I need. Please note there is only one Export for ILedPanel included with the software at any given time.

(If I use an import with List that gives me one instance for every class implementing ILedPanel)

Any suggestions?

like image 702
TimothyP Avatar asked Jun 03 '09 23:06

TimothyP


1 Answers

All of the other answers are pretty old, so they don't mention a relatively new feature in MEF called ExportFactory. This generic class allows you to import ExportFactory<ILedPanel> and create as many instances as you like whenever you need them, so your code would look like this:

[Import(typeof(ILedPanel)]
public ExportFactory<ILedPanel> PanelFactory { get; set; }

public ILedPanel CreateNewLedPanelInstance()
{
    return PanelFactory.CreateExport().Value;
}

This method also satisfies any imports that created part has. You can read more about using the ExportFactory class here.

like image 138
Adi Lester Avatar answered Sep 28 '22 03:09

Adi Lester