This project has moved and is read-only. For the latest updates, please go here.

Dynamic Imports?

Feb 16, 2010 at 4:31 PM


Ok I don't what you might call this but I am basically looking for a way where I might have the following exports:


    Public s As UserControl = New MainShell


    Public s As UserControl = New PersonTab

    Public s As UserControl = New EmployeeTab

On my import, I want to define which I am importing at run time? Is that possible? 

Or should I define an interface like ITab that has a location property and a control property?



Feb 16, 2010 at 9:11 PM

Question do you have multiple places where you are importing these? For example do you have one place where you want to import all the tabs and other places where you want to only import particular tabs?

What you have currently is two different tab exports with different contracts and so you could import the Person.Tab by doing

Public person As UserControl

However since they are unique contract names you cannot import all tabs.

In general for a common contract if you want to distinguish between exports you would use metadata. For example:

<ExportMetadata("Type", "Person")>
Public s As UserControl = New PersonTab

<ExportMetadata("Type", "Employee")>
Public s As UserControl = New EmployeeTab

Then on the importing side you would Import into a Lazy<UserControl, IDictionary<string, object>> and examine the metadata as needed (there are better ways to import the metadata beyond IDictionary but that requires more explanation and gets away from my existing point).

Generally in MEF we don't want people actually importing specific instances because then importer and exporter become to coupled which really hurts maintainability. So in this case the Importer should really not know anything about the concrete types PersonTab/EmployeeTab and they should work through a common abstraction. If the UserControl abstraction isn't enough then perhaps you do need to add another ITab abstraction which contains the functionality you require.

Hope that helps,

Feb 18, 2010 at 1:33 AM


Have a look at the talk below, they'll show you all different ways to do it.

Hope it help.