This project has moved and is read-only. For the latest updates, please go here.

Understanding ContractBasedImportDefinition & GetExports

May 3, 2011 at 8:35 AM
Edited May 3, 2011 at 11:29 AM


I'm not sure if this is a bug or my understanding of how this works is not clear:

In the following code I would have expected exportedTypes to be an empty enumeration (i.e. no items) because of ExportedType class not inheriting from IExportedType (see commented out code on class definition) and the fact that the isPrerequisite parameter is set to true.

Ideally I would only want exports that only match typeof(IExportedType) when the isPrerequisite parameter is set to true or have I misunderstood something?

Any help would be much appreciated.


PS I'm using MEF 2 Preview 3


namespace MEFTest
    class Program
        static void Main(string[] args)
            var p = new Program();
            var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
            var container = new CompositionContainer(catalog);

            var contractName = "MEFTest.IExportedType";
            var typeIdentity = AttributedModelServices.GetTypeIdentity(typeof(IExportedType));
            var definition = new ContractBasedImportDefinition(
                                                    contractName, typeIdentity, null,
                                                    false, true, CreationPolicy.Any);
            var exportedTypes = container.GetExports(definition);
            var export = exportedTypes.FirstOrDefault();
            ExportedType exportedTypeInst;
            if (export != null)
                exportedTypeInst = export.Value as ExportedType;
                var value = exportedTypeInst.Value;

        public IExportedType MyExportedType { get; set; }

    public interface IExportedType
        string Value { get; }

    public class ExportedType //: IExportedType
        public string Value
            get { return "A value."; }


May 3, 2011 at 11:28 AM

Also, in the above, if I use container.GetExports<IExportedType>() the following line I still get back an export even though ExportedType does not inherit from IExportedType.

Then when I call exportedTypes[0].Value complains with "Cannot cast the underlying exported value of type 'MEFTest.ExportedType (ContractName="MEFTest.IExportedType")' to type 'MEFTest.IExportedType'." which I would have expected.  But surely I should not have got the export in the first place?

More info on this would be much appreciated.