[英]How do I setup mef with a class library?
我最近開始在我的應用程序中使用MEF,並且在使用它或測試它在我的主應用程序中作用的類方面沒有問題。 但是,由於我不確定如何設置它,所以我現在剛剛開始為我的應用程序創建許可庫,但是遇到了一些問題。
在我的許可庫中,我有LicenseManager,LicenseValidator和LicenseSigner類:
public class LicenseManager
{
[Import]
private ILicenseValidator _validator;
[Import]
private ILicenseSigner _signer;
public LicenseManager()
{
var catalog = new AssemblyCatalog(System.Reflection.Assembly.GetExecutingAssembly());
var container = new CompsitionContainer();
container.ComposeParts();
}
}
[Export(typeof(ILicenseSigner))]
public class LicenseSigner : ILicenseSigner
{
...
}
[Export(typeof(ILicenseValidator))]
public class LicenseValidator : ILicenseValidator
{
...
}
訪問它們后,我發現驗證者和簽名者均為null
。
我認為是由於我在LicenseManager的構造函數創建容器之前實例化了LicenseManager。 但是,我不確定如何解決該問題,因為LicenseManager旨在用作類庫的唯一入口點。 我可能會創建某種工廠來初始化容器並返回LicenseManager實例,但這會導致不太好的庫API。
我對整個MEF有點陌生。 有什么我可以做得更好的嗎? 我有辦法照顧我的主應用程序中的所有MEF加載嗎? 任何解決方案都比我現在缺乏解決方案要好。
ComposeParts
調用至少需要一個屬性對象才能組成。 你應該在傳遞LicenseManager
作為參數ComposeParts
。 因此,您的全套代碼如下所示:
public class LicenseManager
{
[Import]
private ILicenseValidator _validator;
[Import]
private ILicenseSigner _signer;
public LicenseManager()
{
var catalog = new AssemblyCatalog(System.Reflection.Assembly.GetExecutingAssembly());
var container = new CompsitionContainer(catalog);
container.ComposeParts(this);
}
}
[Export(typeof(ILicenseSigner))]
public class LicenseSigner : ILicenseSigner
{
...
}
[Export(typeof(ILicenseValidator))]
public class LicenseValidator : ILicenseValidator
{
...
}
在我的測試中,以上代碼有效。
另一個想法是將目錄的選擇委托給實現該庫的代碼。 您的構造函數將變為:
public LicenseManager(AggregateCatalog catalog)
{
var container = new CompsitionContainer(catalog);
container.ComposeParts(this);
}
這使實現您的許可庫的程序可以指定導出的來源。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.