Sailor
Sailor

Reputation: 13

Can MEF Support Multiple Plug-ins Using Different Interfaces?

I have a need to load one DLL (Data) using one interface (IDataSender) and another DLL (Message) using another interface (IMessageSender). The code below is generating an error that the DLL being loaded doesn’t support the interface from the other DLL. Looks like each DLL much support all interfaces used by MEF.

Any idea how to load DLLs using different interfaces? I tried using [ImportMany] but that seems to load multiple DLLs using the same interface. Can MEF support multiple Interfaces?

[Import(typeof(IDataSender))]
public IDataSender DataSender;

[Import(typeof(IMessageSender))]
public IMessageSender MessageSender;

catalog_data = new AssemblyCatalog(@".\ABC.Data.dll");
container_data = new CompositionContainer(catalog_data);
container_data.ComposeParts(this);

catalog_message = new AssemblyCatalog(@".\ABC.Message.dll");
container_message = new CompositionContainer(catalog_message);
container_message.ComposeParts(this);

// DLL 1
namespace ABC.Data 
{
    [Export(typeof(IDataSender))]
    public class DataClass : IDataSender
    {
    }
}

// DLL 2
namespace ABC.Message 
{
    [Export(typeof(IMessageSender))]
    public class MessageClass : IMessageSender
    {
    }
}

Thank you for any help offered. I am new to MEF and can't figure out how to get that working.

Kamen

Upvotes: 1

Views: 434

Answers (1)

Panos Rontogiannis
Panos Rontogiannis

Reputation: 4172

You don't need two containers to do this. One is enough. To do so, you need to use an AggregateCatalog that holds both AssemblyCatalogs.

catalog_data = new AssemblyCatalog(@".\ABC.Data.dll");   
catalog_message = new AssemblyCatalog(@".\ABC.Message.dll");
container = new CompositionContainer(new AggregateCatalog(catalog_data, catalog_message);
container.ComposeParts(this);

The problem with your code was that none of the two containers, contained both parts needed to satisfy the imports. Each one contained one of the necessary parts. With the AggregateCatalog you can add multiple catalogs to a container, which is what you actually need. In almost any case, a single container is enough.

Upvotes: 1

Related Questions