This is the 4th and final part of the extensibility series and this time I will talk about MEF (Managed Extensibility Framework). MEF was an open source project on codeplex but in .Net framework 4 (and SL 4) it was included within the framework itself. MEF is a very simple way to allow extensibility in your application.
A short reminder: We have an application consisting of two projects, the main application and the interfaces Dll which we ship to our clients. The client references the interfaces Dll and implements the required interfaces. This time the extensibility project is called Extensibility and it uses MEF to extend our application. To use MEF in .Net 4 project you simply have to reference System.ComponentModel.Composition (from the framework). Now things couldn’t be simpler. All you need to do is to mark your implemented classes with the Export attribute which will allow the MEF mechanism to identify these implementations as your extensibility implementations. You can pass a type to this attribute stating under which type the implemented class will be imported.
So the code didn’t change too much except these things:
and in the main application the loading is much simpler now:
I won’t go into details about the use of MEF but basically I linked the extensibility folder “Extensibility” with the composition container which magically read the dlls from that folder and added the exported classes so that I can later read them using the GetExports method.
I have presented 3 ways of making your application extensible. The first involved reflection only and wasn’t a real extensibility framework but merely a poor man’s solution (which sometimes may be enough). The second solution involved an open source framework (IC#Core) which is a bit obsolete and gives only the infrastructure into which you need to add content. The third solution is the MEF framework which gives you some nice options (such as hot swapping) but if you use it without the source code there is too much “automagical” stuff going on there (at least for me). I think the main take-away here is the design of the application. If you followed the example throughout the four parts you have noticed that due to the design of the application the changes I had to make to move from one extensibility framework to the other were quite minor.
Thank you for reading,