MEF,ImportingConstructor似乎导致错误

时间:2012-10-16 08:36:36

标签: c# c#-4.0 mef

我使用以下代码继续收到以下错误:

Error: "No exports were found that match the constraint: 

ContractName    MefTestSample.Contracts.ICanDoSomethingImportant"

Program.cs如下:

namespace MefTestSample
{
    class Program
    {
        private static CompositionContainer m_Container;


        static void Main(string[] args)
        {
            UseMockedUpTypes();
            ICanDoSomethingImportant cool = m_Container.GetExport<ICanDoSomethingImportant>().Value;
            cool.DoSomethingClever();
            Console.ReadLine();
        }

        private static void UseMockedUpTypes()
        {
            //The commented out section works just by itself.  
            /*
            m_Container =
                new CompositionContainer(
                    new AssemblyCatalog(
                        typeof(MefTestSample.Mocks.ClassesDoNotNecessarly).Assembly));
             */

            //This fails if i dont comment out the [ImportingConstructor] block.
            var assemblyCatalog1 = new AssemblyCatalog(typeof (MefTestSample.Mocks.ClassesDoNotNecessarly).Assembly);
            var myassembly = new AssemblyCatalog(typeof (ServiceLibrary.MoonService).Assembly);
            var aggregateCatalog = new AggregateCatalog(assemblyCatalog1, myassembly);
            m_Container = new CompositionContainer(aggregateCatalog);
        }
    }
}

以下是ClassesDoNotNecessarly的代码:

namespace MefTestSample.Mocks
{
    [Export(typeof(ICanDoSomethingImportant))]
    public class ClassesDoNotNecessarly : ICanDoSomethingImportant
    {
        //private IServicesContract _isc;
        #region ICanDoSomethingImportant Members

        /* This seems to be causing the problem.
        [ImportingConstructor]
        public ClassesDoNotNecessarly([Import("Moon")]IServicesContract isc)
        {
            string temp = isc.DisplayMessage();
            Console.WriteLine(temp);
        }
        */

        public void DoSomethingClever()
        {
            Console.WriteLine("Hehe, I'm actually procrastinating!");        
        }

        #endregion
    }
}

MoonService如下:

namespace ServiceLibrary
{
    [Export(typeof(IServicesContract))]
    public class MoonService : IServicesContract
    {
        public string DisplayMessage()
        {
            return "Moon services were accessed.";
        }
    }
}

我认为问题是什么。如果我按原样保留program.cs,并注释掉ClassesDoNotNecessarly类中的[ImportingConstructor]属性+构造函数,程序将显示该类中的文本。

如果我取消注释[ImportingConstructor]属性n构造函数,我就会开始收到此问题顶部显示的错误。

任何想法都将不胜感激。

1 个答案:

答案 0 :(得分:1)

删除构造函数中的[Import("Moon")],导出未命名,因此无法返回导入。