Tuesday 3 July 2012

Sample of MEF composition factory

I have been introduced to MEF quite while ago, but For sample applications I always like to have small working code to use in order to make sure everything is working before I start on something more complex.

Here I have prepared small example of MEF composition with only one source.
The source is executing location in project.
Note: If you are using MEF in website, the code is on the same place where is your main web.config, unless you specified different location.

Eample:

This class will satisfy all dependencies for class "MyClass" using static composition factory.

  public static class Compose
    {
        /// <summary>
        /// Composes the factory.
        /// </summary>
        public static void ComposeFactory(object myObject)
        {
            var catalog = new AggregateCatalog(
                new AssemblyCatalog(System.Reflection.Assembly.GetExecutingAssembly()),
                new DirectoryCatalog(@"."));

            foreach (var container in catalog.Parts.Select(part => new CompositionContainer(catalog)))
            {
                container.ComposeParts(myObject);
            }        }
    }


Where usage might be such as:

public class MyClass(){

public MyClass(){
   Compose.ComposeFactory(this);
}

[Import(typeof(ILogger))]
 public ILogger Logger{get;set;}

// some of your implementation
}


Point of interest.

MEF has two major import types: Import and ImportMany

[Import] or [Import(typeof(IMyInterface))]

Import is used where you want to import only one item.
Unless you specify the typeof MEF will inspect the object of its decoration and automatically try to satisfy the dependency from catalog.
My preference is the second option, which allows you to be specific which object is supposed to satisfy this injection.

Import can be null.


[ImportMany] or [ImportMany(typeof(IMyInterface))]

Import many has to have at least one item, otherwise you will receive an exception.
Again you can leave the satisfaction of the dependency on MEF or be specific.

No comments:

Post a Comment