Tuesday, 2 February 2010

MEF for non Silverlight applications

Here is the solution to the problem that System.ComponentModel.Composition.Initialization.dll  is missing in VS2010 Beta 2. The problem was that  the following method is not available for non Silverlight applications.

System.ComponentModel.Composition.PartInitializer.SatisfyImports(this)

The solution is to build the Container by hand…

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;

namespace CCP.BusinessLogic
{
    public class Test
    {
        [Import] // Menas this class needs a WordProcessor
        public WordProcessor wordProcessor { get; set; }

        public Test()
        {
            InitializeMef();

        }

        private void InitializeMef()
        {
            DirectoryCatalog directoryCatalog = new DirectoryCatalog(@".");
            CompositionBatch batch = new CompositionBatch();
            batch.AddPart(this);
            CompositionContainer container = new CompositionContainer(directoryCatalog);
            container.Compose(batch);
        }

    }
}