Monday, October 31, 2011

Auto-Wiring EventAggregator Subscription in Caliburn.Micro


Just wanted to make a quick note about how to get auto-wiring of the EventAggregator subscription up and running for Caliburn.Micro. What I want to accomplish is to avoid having to write this:


… and instead make this "just happen" when a type implements IHandle. And as you can see from the code above, the IoC I use here is MEF.

So I haven't used MEF before, but I found this post ("Introduction to InterceptingCatalog – Part I") by Piotr Włodek and figured that with a little bit of tweaking this should work.

This code relies on the MEFContrib project up on CodePlex/GitHub, so if you haven't already downloaded it you can get it from there or just NuGet-it into your project;


To be able to get any class that implements IHandle to list itself as a subscriber in the EventAggregator, we need to hook into the creation pipeline in MEF. And MEF hasn't any hooks that let us do this, but fortunately MEFContrib has and it's called an InterceptingCatalog.

The InterceptingCatalog takes two arguments; a ComposablePartCatalog and an InterceptionConfiguration. It's the InterceptionConfiguration that let's us provide an interceptor that can do the auto-wiring for us. But first, let's create the class that will do the interception - the EventSubscriptionsStrategy:


This object creation strategy will be added to the MEF creation pipeline. This class will be called for every object resolved from MEF, but in this case we're only interested in those who implements the IHandle interface. So if the casting succeeds we now that this is class that will want to subscribe to events. So by using the Intercept method from the IExportedValueInterceptor interface, we can tell the EventAggregator that this object is an event subscriber.

The only thing missing then, is to plug our EventSubscriptionStrategy into MEF;


This is from the default AppBootstrapper from Caliburn.Micro with the changes I made to get the EventSubscriptionStragegy registered in MEF marked in red.


Caliburn.Micro: - This is a WPF/SL/WP7 framework along the same lines as PRISM from Microsoft Patterns & Practices. Only much smaller (in size, not necessarily feature set) and much more "opinionated".

MEF Contrib: and - Open source extensions to the Managed Extensibility Framework (MEF). In other words; extending the extensibility with extensions…

No comments: