Monday, January 25, 2010

What is Managed Entity Framework - MEF

After joining in new company I rarely get time to learn new technologies than my previous company.Obviously its due to more responsibilities.But this week end I was managed to find some time to learn MEF (Managed Entity Framework) which was introduced some time back.

In simple words its all about Export,Import and Composition.ie you export a type or property then you import into another property which is present in another class.For this to happen there should be somebody in the middle.That is composition.

The export and import takes place by using attributes.Just decorate the class or property with the attribute export or import to achieve the functionality.For composition you just need one line code :-)

Exporting one type

[Export("Emp")] 
public class Employee
{
}


The above code just exports one class.Lets see how this is being used or imported.




public class EmployeeViewModel
{
[Import ("Emp")]
public Employee Current { get; set; }
}



The employee view model class receives the exported type as Current.This code it not completed.To complete the code we need to compose.It is done by the line below.




public EmployeeViewModel()
{
PartInitializer.SatisfyImports(this);
MessageBox.Show(Current.ToString());
}


This is the constructor of EmployeeViewModel class and the first line does the composition and after that if we access the object it will be initialized and ready for use.In this case it will display the default ToString method’s output ie the class name.

This is the basic concept of MEF.This can be used in data binding and for collection types etc…Next time will discuss about a data binding and MEF.

The project contains a reference to the dll System.ComponentModel.Composition.dll.You can locate this file from the attached sample or in the Silverlight 4 installation.

Sample can be downloaded from here.

1 comment:

Sameer C. Thiruthikad said...

Good to know you are back in blogging. :)

See this as well on MEF:
http://ctlabs.blogspot.com/2009/10/mef-in-net-40visual-studio-2010-simple.html