2012-08-13 83 views
0

我有一個項目,其中包含兩個模塊,一個基礎設施(Common庫)和Shell如何從MEF中的基礎結構庫中導出類?

enter image description here

注意CommonFooService,這其中有一個ExportAttribute

[Export] 
public class FooService 
{ 
} 

,則應當由Module1Module2使用,但它引發了我的錯誤,如果我有ImportAttribute。請注意評論。

[ModuleExport("Module1.ModuleInit", typeof(Module1.ModuleInit))] 
public class ModuleInit : IModule 
{ 
    private readonly IRegionManager _regionManager; 
    public IServiceLocator _serviceLocator; 

    // [Import(AllowRecomposition=true)] 
    public FooService _service; 

    [ImportingConstructor] 
    public ModuleInit(IRegionManager regionManager, IServiceLocator serviceLocator) 
    { 
     _regionManager = regionManager; 
     _serviceLocator = serviceLocator; 
    } 

    public void Initialize() { } 
} 

此代碼與Module2相同。

初始化模塊「Module2.ModuleInit」時發生異常。 - 異常消息是:構圖保持不變。由於以下錯誤,更改被拒絕: 組合產生了單個組合錯誤。根本原因是 下面提供。查看 的CompositionException.Errors屬性更詳細的信息。

1)一個以上的出口發現該約束 「((exportDefinition.ContractName == 「Common.FooService」)AndAlso (exportDefinition.Metadata.ContainsKey( 「ExportTypeIdentity」)AndAlso 「Common.FooService匹配」 .Equals(exportDefinition.Metadata.get_Item( 「ExportTypeIdentity」))))」。

導致:無法在部件'Module1.ModuleInit'上設置導入'Module1.ModuleInit._service (ContractName =「Common.FooService」)'「。 Element:Module1.ModuleInit._service (ContractName =「Common.FooService」) - > Module1.ModuleInit - > AssemblyCatalog(Assembly =「Module1,Version = 1.0.0.0,Culture = neutral, PublicKeyToken = null」 )

爲什麼我收到此異常?我只是導出一個對象。我想知道發生了什麼以及如何解決它。

請隨意下載它,這是非常小的項目。 Download the compact project

+0

*發現多個導出符合約束...... * – 2012-08-13 23:11:14

+0

我知道,但我不明白爲什麼MEF導出了兩個'FooServices'。我的意思是,'FooService'的想法應該是所有模塊的同一個實例 – 2012-08-13 23:25:58

回答

0

這應該只是一個評論,但我沒有足夠的代表來做到這一點呢。無論如何,它看起來像一個範圍問題。我相信MEF v1應該自動將出口作爲單身處理,但我認爲它在第2版中已被逆轉 - 不確定您使用的是哪個版本。我最近使用Microsoft.Composition(MEF for MVC)遇到了一個問題,並通過使用HTTP請求級別範圍確定來獲取整個請求生命週期中的單個實例。

[System.Composition.Export(typeof(ICustomDbContext))] 
[System.Composition.Shared(Boundaries.HttpRequest)] 
public class CustomDbContext : ICustomDbContext { ... } 
0

解決方案:你去通過每個項目除了殼牌項目,並期待在引用;做到以下幾點:

  • 只是刪除unityextension參考,因爲您使用MEF
  • 集「通用」引用屬性「複製本地」設置爲False
  • 集「Microsoft.Practices.Prism」引用屬性「複製本地」設置爲False
  • 集‘Microsoft.Practices.Prism.MefExtensions’引用屬性‘複製本地’設置爲False
  • 集‘Microsoft.Practices.Prism.ServiceLocation’引用屬性‘複製本地’設置爲False
  • 設置「S ystem.ComponentModel.Composition」引用屬性 「複製本地」 設置爲False

轉到引導程序類,補充一點:

protected override void ConfigureAggregateCatalog() 
     { 
      base.ConfigureAggregateCatalog(); 

      // Add this assembly to the catalog. 
      this.AggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof(Bootstrapper).Assembly)); 

      // Add the FooService assembly 
      this.AggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof(FooService).Assembly)); 
     } 

然後取消對[導入(AllowRecomposition)和FooService接口在你的模塊。

在運行項目之前,需要轉到Visual Studio菜單中選擇Build - > Clean Project。這將刪除他們以前複製本地真實的所有dll文件。