Software Architecture -C#-4.0 – New Feature – Why/What/How of Managed Extensibility Framework -MEF , Sample Calculator Code

According to MSDN:

The Managed Extensibility Framework or MEF is a library for creating lightweight, extensible applications. It allows application developers to discover and use extensions with no configuration required. It also lets extension developers easily encapsulate code and avoid fragile hard dependencies. MEF not only allows extensions to be reused within applications, but across applications as well.


I have copied few definitions from MSDN as:

Composable part (or, simply, part)—A part provides services to other parts and consumes services provided by other parts. Parts in MEF can come from anywhere, from within the application or externally; from an MEF perspective, it makes no difference.
Export—An export is a service that a part provides. When a part provides an export, it is said that the part exports it. For example, a part may export a logger, or in the case of Visual Studio, an editor extension. Parts can provide multiple exports, though most parts provide a single export.
Import—An import is a service that a part consumes. When a part consumes an import, the part imports it. Parts can import single services, such as the logger, or import multiple services, such as an editor extension.
Contracts—A contract is an identifier for an export or an import. An exporter specifies a string contract that it provides, and an importer specifies the contract that it needs. MEF derives contract names from the types that are being exported and imported, so in most cases you don’t have to think about it.
Composition—Parts are composed by MEF, which instantiates them and then matches up exporters to importers.

Sample :
Download sample code from here Rename file as mefdemoappsol.zip and extract the code
In this example, we will implement different methods of calculator via Managed Extensibility Framework-MEF.
1. Create a C# Console application with name “MEFDemoApp” with solution name as “MEFDemoAppSol”.
2. Add a C# Library project to solution with name “MEFAppLib”.
3. Add reference to “System.ComponentModel.Composition.dll” in both projects.
4. Add reference of console application (MEFDemoApp) project in Library project(MEFAppLib).
5. Change Build Output path of C# library project in project properties to “..\\MEFDemoApp\\bin\\Debug”, so that dll created for Library project is copied to console project.
6. Create an interface for calculation in console project as:

 public interface ICalRule 
        {
             int GetResults(int First, int Second);                        
        }

7. In C# library, add two implementations for above interface is shown as:

  [Export(typeof(ICalRule))]
    public class CalRule1 : ICalRule
    {
        public int GetResults(int First, int Second)
        {
            return First + Second;
        }
    }
    [Export(typeof(ICalRule))]
    public class CalRule2 : ICalRule
    {
        public int GetResults(int First, int Second)
        {
            return First - Second;
        }
    }

Note here that Export attribute is used to show that this is a service that is provided to others.
8. In console application, import is used as:

        [ImportMany]
        public  ICalRule[] CalRules { get; set; }

9. Composition process is created and extensions are loaded from library project as:

// Compose 
DirectoryCatalog catalog = new DirectoryCatalog(Environment.CurrentDirectory);
CompositionContainer container = new CompositionContainer(catalog);
container.ComposeParts(this);                       

10. Testing operations on methods avaliable via MEFcan be done as:

    public void ShowResults()
    {
        foreach (var d in CalRules)
            {
            int ans = d.GetResults(3, 6);
          Console.WriteLine(string.Format("Rule {0}: {1}", d.GetType(), ans));
            }
            Console.ReadLine();
        }

11. Collectively, the console side of application will look like as:

class Program
    {
        [ImportMany]
        public  ICalRule[] CalRules { get; set; }
 
        private Program()
        { 
            // Compose 
            DirectoryCatalog catalog = new DirectoryCatalog(Environment.CurrentDirectory);
            CompositionContainer container = new CompositionContainer(catalog);
            container.ComposeParts(this);                       
 
        }
        public void ShowResults()
        {
            foreach (var d in CalRules)
            {
                int ans = d.GetResults(3, 6);
                Console.WriteLine(string.Format("Rule {0}: {1}", d.GetType(), ans));
            }
            Console.ReadLine();
        }
        static void Main(string[] args)
        {
            Program pro = new Program();
            pro.ShowResults();           
        }
 
    }

12. On running the application, results will l.ook like as:

Rule MEFAppLib.CalRule1: 9
Rule MEFAppLib.CalRule2: -3

Conclusion:
In the above example, we have created two extensibility examples by implementing interfaces using import and export attributes.

References:
The sample in this post is simplified version of calculator discussed by MSDN Team at:
http://msdn.microsoft.com/en-us/library/dd460648.aspx
MSDN Team have provided complex cases, but to make things simple I have provided a new version of calculator via MEF, hope you will like it.

Advertisements

3 Responses to Software Architecture -C#-4.0 – New Feature – Why/What/How of Managed Extensibility Framework -MEF , Sample Calculator Code

  1. Me says:

    Why the hell someone wants to write his religion in “CV” ? Muslim ? So what ? So silly ? What if I’m Christian or atheist ? You could kill me ? Hello ? Can’t read your post, I’m repulsed.

    • shahzadsb says:

      Thanks for your comments about my blog. Your concerns are very valuable to me. I really appreciate that.

      Now coming back to your question. Have you ever seen national id card which is used to identify a person. It has all information like name, age (date of birth), sex, martial status, region and address. Actually all these information are vital to identify a person. In my blog I have put all these information, just to identify me. Answer to question “Who is Shahzad?”

      Now coming to second part, “Is Islam really a region of hate or terrorism?” This whole theory is sponsored by certain groups specially media tycoons. TV, radio, newspapers and magazines, are influenced by their investors or owners who have certain agendas and who want to promote certain values and points of view. So this whole thing is Mind Control game which is against Muslim these days.

      Read the article below, which explain Islam and its values.
      http://www.al-islami.com/islam/religion_of_peace.php
      [Read all 5 pages]
      Secondly, read book:
      http://www.islamareligionofpeace.com/

      Don’t afraid about Islam and Muslims. Get close to them, you will find them niece and friendly.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: