2011-06-02 46 views
1

我想在我的ASP.NET網頁表單(SharePoint)應用程序中使用MEF從運行時的目錄加載一些控件。我沒有收到任何錯誤,但控件沒有被加載。使用MEF與asp.net網頁表單應用程序(SharePoint)

這裏是我的代碼 -

aspx.cs

public partial class SampleMEF : System.Web.UI.Page 
    { 
     [ImportMany(typeof(IControlLoader))] 
     IEnumerable<Lazy<IControlLoader, IControlLoaderMetaData>> controls; 
     private CompositionContainer _partsContainer; 
     private AggregateCatalog _catalog; 
     private string _partsPath; 

     /// <summary> 
     /// default constructor 
     /// </summary> 
     public SampleMEF() 
     { 
     } 

     /// <summary> 
     /// Initialize the page 
     /// </summary> 
     /// <param name="e"></param> 
     protected override void OnInit(EventArgs e) 
     { 
      _partsPath = SPUtility.GetGenericSetupPath(@"TEMPLATE\LAYOUTS\MEFProtoType\Parts"); 
      _catalog = new AggregateCatalog(); 
      DirectoryCatalog c = new DirectoryCatalog(_partsPath, "*.dll"); 
      _partsContainer = new CompositionContainer(c); 
      _partsContainer.ComposeParts(this); 
     } 

     protected void Page_Load(object sender, EventArgs e) 
     { 
      foreach(Lazy<IControlLoader, IControlLoaderMetaData> i in controls) 
      { 
       SPPControl ctrl = i.Value.LoadControl(); 
       lbxControls.Items.Add(new ListItem(ctrl.Name, ctrl.ControlID.ToString())); 
      } 
     } 
    } 

合同

/// <summary> 
    /// Contract for Imports and Exports 
    /// </summary> 
    public interface IControlLoader 
    { 
     SPPControl LoadControl(); 
    } 

    /// <summary> 
    /// Exports metadata 
    /// </summary> 
    public interface IControlLoaderMetaData 
    { 
     string ControlID { get; } 
    } 

樣品出口

[Export(typeof(IControlLoader))] 
    [ExportMetadata("ControlID", "7a6c6288-ab52-4010-8c56-79959843ec7c")] 
    public class ctrlAccordion : IControlLoader 
    { 
     #region IControlLoader Members 

     public SPPControl LoadControl() 
     { 
      SPPControl ctrl = new SPPControl("Accordion", new Guid("7a6c6288-ab52-4010-8c56-79959843ec7c"), 5); 
      return ctrl; 
     } 

     #endregion 
    } 

我能夠看到在部件目錄中複製的DLL。但我無法加載部件。導入未填充且爲空。

我正在使用.Net Framework 3.5並從MEF Codeplex下載了MEF dll並自己簽署了程序集。

任何想法?

回答

2

好吧,我最終發現了這個問題。只有我簽名並將dll添加到全局程序集,我才能加載部分dll。但我不明白什麼DirectoryCatalog加載文件夾。

底線:如果dll只在部分文件夾中,而不在GAC中,則不會被加載。

1

嘗試從任意位置加載程序集時可能會出現問題。 this blog post的「裝配加載問題」部分有關於此的一些信息並鏈接到更多信息。

您也可以檢查調試器中的目錄,看它是否加載了任何零件。

+0

是的,這是我如何調試和檢查目錄對象。它只顯示加載的文件 - 3,加載的程序集 - 0,零件 - 0.這3個加載的文件實際上都是有效的dll,其中有輸出。但是,一旦我簽署並將其放入GAC,它就會起作用! – NLV 2011-06-03 05:36:39

+0

+1爲博客鏈接。 – NLV 2011-06-03 05:37:15

+0

@NLV對他們進行簽名而不將他們放入GAC也可能工作。給組件一個強大的名字(即簽名)可以防止它被加載兩次。如果您在正常的bin文件夾和部分文件夾中都有未簽名的codeplex MEF DLL,那麼可能會加載MEF DLL的兩個副本,並且您的部件中的ExportAttrributes未被識別爲與您的容器的ExportAttribute相同正在尋找。 – 2011-06-03 14:37:15