First download MEF assembly from Microsoft url:
Managed Extension Framework, called Mef, is usefull when you want to extend your application. To do it, Mef allow Dependency injection between composant or layers.
When use Unity and Mef ?
-use Unity to do dependency injection during development when you know all components
-use MEF for components that will come in future, or when you want your application splitted in assembly that are not in the same solution or you want not to have reference (prefering to “bind” assembly) – interesting in a plugin architecture…
So, you can use both each one having its own purpose.
We will create three assemblies:
-Contracts.dll which provides all contracts
-MyBusinessComponent.dll which provides the implementation of our business
-Form1 : a winform where we will call dynamically our business layer through MEF and without any reference on the winform project
1/Create a Contracts assembly:
add to your solution a new Class library project and call it Contracts
add a IBusinessService interface
2/create our business assembly
add a second class library project called MyBusinessComponent:
add a reference on MEF assembly (System.ComponentModel.Composition.CodePlex ) in this project in order to expose our business service methode:
Create a MyBusinessService class and implement IBusinessService as below :
an export attribute decorate MyBusinessService class with the interface we want to expose (here IbusinessService). You have to add a MEF namespace
3/Create a winform that will act as a presentation layer:
Add a windows form application to the solution
add a control button and a label called it LabelInfo
add a MEF reference as follows:
add also a reference only on Contracts assembly :
Now on winform code :
-Use Import attribute with the type of the interface and define a IBusinessService property
-Create a DirectoryCatalog and pass the location of your BusinessService assembly (you can use a relative path as below)
– Instantiate a compositioncontainer and pass the DirectoryCatalog: MEF will understand that all assemblies to explore are in the path of your DirectoryCatalog. MEF will get all attributes (here export of our business service) by reflection.
-Finally, call ComposeParts on form class, it enables Mef container to make the dependency mapping (using Export and Import Attribute)
all work fine and note that there isn’t any reference to BusinessService assembly.
Conclusion: in this sample, MEF is used as a third part that manage externe dependencies from different assemblies.