Subscribe / Unsubscribe Enewsletters | Login | Register

Pencil Banner

How to work with the Managed Extensibility Framework in C#

Joydip Kanjilal | July 11, 2016
The Managed Extensibility Framework in .Net avoids fragile hard dependencies in your code and builds applications that are loosely coupled, lightweight, and extensible

Now, consider the following interface named ILogger given below.

public interface ILogger

   {

       string Message { get; set; }

   }

The following classes FileLogger and DbLogger implement the ILogger interface.

[Export]

   public class FileLogger : ILogger

   {      

       public string Message

       {

           get;set;

       }

   }

[Export]

   public class DbLogger : ILogger

   {

       {

           get; set;

       }

   }

At first glance you might assume that MEF is like a DI container. However, although MEF looks like a DI container, it mainly aims at extensibility. In essence, MEF takes advantage of an attribute based discovery mechanism to promote extensibility sans the need of configuring the components. You don't need any registration -- you just need to mark your types with the Export attribute and it does all for you. Unlike Unity, when using MEF, you can just mark your classes using attributes without the need of registering them individually. The exported values are all stored in a container. The following class shows how you can build a custom MEF container and store inside it all the exports from the directory where the current executing assembly resides.

public static class MEFContainer

   {

       private static CompositionContainer compositionContainer = null;

       public static CompositionContainer Container

       {

           get

           {

               if (compositionContainer == null)

               {

                   var directoryCatalog =

                        new DirectoryCatalog(

                       Path.GetDirectoryName(

                       Assembly.GetExecutingAssembly().Location));

                   compositionContainer = new CompositionContainer(directoryCatalog);

               }

               return compositionContainer;

           }

       }

   }

The following code snippet illustrates how you can retrieve an instance of type FileLogger via the container.

FileLogger fileLogger = MEFContainer.Container.GetExportedValue<FileLogger>();

Similarly, to retrieve an instance of type DbLogger, you can use the following code snippet.

DbLogger dbLogger = MEFContainer.Container.GetExportedValue<DbLogger>();

Source: Infoworld 

 

Previous Page  1  2 

Sign up for CIO Asia eNewsletters.