views:

32

answers:

1

I have created a MEF plugin control that I import into my app. Now, I want the plugin to be able to import parts from the app. I can't figure how setup the catalog in the plugin, so that it can find the exports from the app. Can somebody tell me how this is done? Below is my code which doesn't work when I try to create an AssemblyCatalog with the current executing assembly.

[Export(typeof(IPluginControl))]
public partial class MyPluginControl : UserControl, IPluginControl

    [Import]
    public string Message { get; set; }


    public MyPluginControl()
    {
        InitializeComponent();
        Initialize();
    }

    private void Initialize()
    {
        AggregateCatalog catalog = new AggregateCatalog();
        catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
        CompositionContainer container = new CompositionContainer(catalog);
        try
        {
            container.ComposeParts(this);
        }
        catch (CompositionException ex)
        {
            Console.WriteLine(ex.ToString());
        }

    }
}
+2  A: 

You don't need to do this.

Just make sure that the catalog you're using when you import this plugin includes the main application's assembly.

When MEF constructs your type in order to export it (to fulfill the IPluginControl import elsewhere), it'll already compose this part for you - and at that point, will import the "Message" string (though, you most likely should assign a name to that "message", or a custom type of some sort - otherwise, it'll just import a string, and you can only use a single "string" export anywhere in your application).

When MEF composes parts, it finds all types matching the specified type (in this case IPluginControl), instantiates a single object, fills any [Import] requirements for that object (which is why you don't need to compose this in your constructor), then assigns it to any objects importing the type.

Reed Copsey
Thanks, everything you said helped and it works now!
John_Sheares