MEF unsupported cycle during composition #MEF #WinRT #Metro

Sep 6, 2012 at 12:16 PM

I am using MEF for web and Windows store apps v. 1.0.15 and I require a cyclic composition on my items.

 

    [Export]
    public class ItemHolder
    {
        [ImportMany]
        public IEnumerable<IItem> Items { get; set; }
    }

    public interface IItem
    {
        ItemHolder Holder { get; set; }
    }

    [Export(typeof(IItem))]
    public class ItemA : IItem
    {
        [Import]
        public ItemHolder Holder { get; set; }
    }

    [Export(typeof(IItem))]
    public class ItemB : IItem
    {
        [Import]
        public ItemHolder Holder { get; set; }
    }

    [Export(typeof(IItem))]
    public class ItemC : IItem
    {
        [Import]
        public ItemHolder Holder { get; set; }
    }

In the above scenario I can access any IItem from any IItem as required, but when I am getting composition Exception.

Detected an unsupported cycle for part 'ItemHolder'. To construct a valid cycle, at least one part in the cycle must be shared, and at least one import in the cycle must be non-prerequisite (e.g. a property).
 -> required by import 'Holder' of part 'ItemA'
 -> required by import 'item' of part 'IItem[]'
 -> required by import 'Items' of part 'ItemHolder'
 -> required by initial request for contract 'ItemHolder'

I am lost here, why part of cycle should be shared? It use to work in MEF (.NET framework 4.0) and how do I resolve it now?

Sep 6, 2012 at 8:30 PM

G'day - 

You can make ItemHolder shared, like this:

    [Export, Shared]
    public class ItemHolder
    {
        [ImportMany]
        public IEnumerable<IItem> Items { get; set; }
    }

This works in 'big MEF' (.NET 4.0 and 4.5 full framework) because parts are shared by default in CompositionContainer.

In Microsoft.Composition you need to add the [Shared] attribute explicitly if you want a part to be shared, since the default is non-shared.

Hope this helps,

Nick