Dynamic Imports?

Feb 16, 2010 at 3: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:

 

 <Export("Shell")>
    Public s As UserControl = New MainShell

 

 <Export("Person.Tab")>
    Public s As UserControl = New PersonTab

 <Export("Employee.Tab")>
    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?

 

 

Developer
Feb 16, 2010 at 8: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

<Import("Person.Tab")>
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:

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

<Export>
<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,
Wes

Feb 18, 2010 at 12:33 AM

Hi,

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

http://channel9.msdn.com/shows/SilverlightTV/Silverlight-TV-Episode-4-3-Steps-to-MEF-Export-Import-Compose/

Hope it help.

Cheers,

Brandon