With .NET 4.0 Microsoft ships a new composition container named Managed Extensibility Framework (MEF). MEF already have two feathers in the cap: Visual Studio 2010 editor extensions and Intellipad, the DSL editor of
OSLO SQL Server Modeling.
MEF can be used to achieve the object-oriented programming principle “Open-Closed Principle (OCP)” software entities (classes, modules, functions, etc.) should be open for extension, but closed for modifications. What that means to me is that it should be possible to extend the application without modifying its case. For example, if an application was programmed to log to an text file and a later point of time if the requirement is to write to a console, then it should be possible to do so without modifying the source code. To achieve OCP we need to provide extension points. We can found a lot of such examples in the addin model of the applications like Visual Studio text editor, Outlook, WinAmp etc.
The fundamental concepts in MEF are : Import, Export, Composable Part, Contracts, Composition. The following diagram shows how they are related :
A Composable Part should have at least one or more Export or Import. Imports and Exports are defined using Contracts. A catalog of parts is used by container to compose the parts. Lets see a simple example of this.
Let’s define a contract first for the Imports and Exports. I have a ILogger interface as contract.
A ConsoleLogger class which implements ILogger and writes to the Console.
At line no. 2 the we import System.ComponentModel.Composition namespace from the references assembly System.ComponentModel.Composition one of the MEF assembly. This is required for the ExportAttribute used at line no. 7. By using Export attribute we have exported the ConsoleLogger as a composable part .
Now we have a contract and an export. Lets see the code to import. To import we need to use the ImportAttribute like this.
Now lets compose it.
On start of the ComposedApplication, the first thing we do is to compose it as in line 20. For this application since all the required parts viz. Imports and Exports, are in the same assembly I am using AssemblyCatalog at line no 27 and initializing with the executing assembly. Then the CompositionContainer is instantiated with this catalog as constructor parameter. To get the dependency fulfilled or the part composed, we need to call the ComposeParts method on the container as in line 29. After the composition succeeds, all the imports the current class will be fulfilled like the Logger property.
Where is Python absolutely necessary in Intellipad? http://social.msdn.microsoft.com/Forums/en-US/oslo/thread/7a440138-1417-4414-89c3-2e6ecd2ab430
Managed Extensibility Framework in the Editor http://msdn.microsoft.com/en-us/library/dd885013.aspx