【问题标题】:MEF, ImportingConstructor seems to be causing an errorMEF,ImportingConstructor 似乎导致错误
【发布时间】:2012-10-16 08:36:36
【问题描述】:

我不断收到以下代码的以下错误:

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 构造函数,我就会开始收到此问题顶部显示的错误。

任何想法将不胜感激。

【问题讨论】:

    标签: c# c#-4.0 mef


    【解决方案1】:

    去掉构造函数中的[Import("Moon")],Export没有命名,所以Import不能作为return命名。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多