2012-10-16 49 views
1

我不断收到以下错误与下面的代码:MEF,ImportingConstructor似乎导致了错误

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

删除构造函数中的[Import("Moon")],导出没有被命名,所以导入不能被返回。