This project has moved. For the latest updates, please go here.

MEF as an event bus

Jan 18, 2009 at 8:21 AM
Edited Jan 18, 2009 at 8:37 AM
The possibility to import/export methods in MEF could be a solution for writing an event bus using MEF.
The subscribers export their methods, the publishers call the methods using the imported delegate.

While playing around with these features, I had some issues down the road.

1. Only support for Action<...> and Func<...>
MEF [Export]s methods only as Action<...> or Func<...>. If you try to use your own specific delegate on the [Import] side, you receive a TypeMismatchBetweenImportAndExport exception.
A side effect of having to use Action<...> or Func<...> on [Import] side is, that your intellisense look like void Action<string, int> (string arg1, int arg2) instead of  ProgressChangedEventHandler(string progressMessage, int progressPercentage)

Does an attribute exist to specify the type of delegate you want to use on Export side?
eg: [ExportDelegate(typeof(ProgressChangedEventHandler))]

2. Multicast delegates
To be able to assign multiple methods to the same [Import] delegate, you're required to create a collection of delegates on the [Import] side. MEF does not automatically assign them to the multicast delegate, you receive a cardinality exception instead.
A side effect of having a collection is that you cannot just write ProgressChanged("Done", "100"), you have to write a foreach around it to invoke each delegate in the collection separately.

3. Import or Export are sealed
In this scenario, for readability purposes only, it would be handy to be able to inherit these attributes, eg:
EventPublisherAttribute: ImportAttribute
EventSubscriberAttribute: ExportAttribute