CompositionHosts exports run in parallel sometimes inject null to imported value

Jun 30, 2015 at 1:18 PM
Hello,

I am working on a multi-tenant application, where every tenant has its own CompositionHost (System.Composition.Hosting.CompositionHost) with the same part types. When I try to get export of the same type from two CompositionHosts at the same time (in parallel), one of them will inject null into ImportingConstructor (or imported property as well).

Just to clarify - I am not using the same container in multiple threads. There are many CompositionHosts and every parallel export uses a different one.

The problem happens only on the first export of given type. It does not occur when exports are done sequentially.

Below I attach minimal code that reproduces my issue. Please bear in mind that due to parallel execution the issue may not always reproduce. Is there something wrong with the way I use CompositionHosts or is it a bug in MEF2?
  [Export]
    public class InjectedClass {}

    [Export]
    public class TestA
    {
        [ImportingConstructor]
        public TestA(InjectedClass injectedInstance)
        {
            if (injectedInstance == null)
                throw new ArgumentNullException("injectedInstance");
        }
    }

    class Program
    {
        static void Main()
        {
            const int containersCount = 2;
            var compositionContainers = Enumerable.Range(0, containersCount).Select(_ => InitContainer()).ToList();
            Parallel.ForEach(compositionContainers, cc => cc.GetExport<TestA>());
        }

        private static CompositionHost InitContainer()
        {
            var containerConfiguration = new ContainerConfiguration();
            containerConfiguration.WithPart<InjectedClass>();
            containerConfiguration.WithPart<TestA>();
            return containerConfiguration.CreateContainer();
        }
    }