A day with .Net

My day to day experince in .net

Archive for the ‘Managed Extensibility Framework’ Category

Abstract class with MEF

Posted by vivekcek on October 12, 2012

I hope you have some experience in MEF. Sorry this is not a beginner article on MEF.

You can read my old post here. Managed Extensibility Framework

In this article i am using Abstract classes instead of interfaces for define our contracts.
Why i used abstract classes because you are not forced to implement the methods in your child classes.

1. Create a Visual Studio 2012 Console c# project.

2. Add reference to ‘System.ComponentModel.Composition’.

3. Create an abstract class like below.

 public abstract class AbstractClass
    {
        public abstract void DisplayName();
    }

4. Create a class A.

using System;
using System.ComponentModel.Composition;

namespace MEF
{
    [Export(typeof(AbstractClass))]
    class A:AbstractClass
    {
        public override void DisplayName()
        {
            Console.WriteLine("From class B");
        }
    }
}

5. Create a class named B.

using System;
using System.ComponentModel.Composition;
namespace MEF
{
    
    [Export(typeof(AbstractClass))]
    class B: AbstractClass
    {
        public override void DisplayName()
        {
            Console.WriteLine("From class B");
        }
    }
}

6. Now change your Program class like below.

using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
namespace MEF
{
    class Program
    {        
        static void Main(string[] args)
        {
            Assembler asm = new Assembler();
            asm.DoWork();
        }

    }
    class Assembler
    {
        [ImportMany(typeof(AbstractClass))]
        List<AbstractClass> Factory = new List<AbstractClass>();
        public void DoWork()
        {
            var catlog = new AggregateCatalog();
            catlog.Catalogs.Add(new AssemblyCatalog(System.Reflection.Assembly.GetExecutingAssembly()));
            var container=new CompositionContainer(catlog);
            container.ComposeParts(this);
        }
    }
}
Advertisements

Posted in Managed Extensibility Framework | Tagged: , , | Leave a Comment »