Question about use of MefServiceLocator

May 4, 2013 at 4:02 PM
Why doesn't the compositionContainer get resolved in Class Foo shown below?
    class Program
    {
        static void Main(string[] args)
        {
            Test mytest = new Test();
        }
    }

    public class Test
    {
        public Test()
        {
            ComposeMefContainer();

            Foo foo = new Foo();
        }

        private void ComposeMefContainer()
        {
            CompositionContainer _container;
            var catalog = new AggregateCatalog(new DirectoryCatalog("."),
                          new AssemblyCatalog(Assembly.GetExecutingAssembly()));
            _container = new CompositionContainer(catalog);
            _container.ComposeParts(this);

            var mef = new MefServiceLocator(_container);
            ServiceLocator.SetLocatorProvider(() => mef);
        }
    }

    public class Foo
    {
        [Import]
        Bar abar;

        public Foo()
        {
            //I know I can do the following
            var bar = ServiceLocator.Current.GetInstance<Bar>();

            //Why doesn't this work?
            var compositionContainer = ServiceLocator.Current.GetInstance<CompositionContainer>();
            compositionContainer.SatisfyImportsOnce(this);
        }
    }

    [Export]
    public class Bar
    {
        public string Name {get; set;}

        public Bar()
        {
            Name = "Tom";
        }
    }

}