簡體   English   中英

在MEF上下文中使用泛型

[英]Using Generics in MEF-Context

我想將泛型與MEF-“ [ImportMany(....))]”結合使用,但出現編譯錯誤。

以下代碼無需使用泛型即可正常工作 :工廠類“ HelperOneFactory”(請參見下文)正在搜索“ IHelperOne”接口的所有實現。 從該列表中獲取第一個沒有元數據值“原始”的對象。 如果不存在,那么它將不檢查元數據值就采用第一個方法。

/// =====================================================================================
/// factory-implementation for interface-type "IHelperOne"  (==> works fine)
/// =====================================================================================
[Export(typeof(HelperOneFactory))]
public class HelperOneFactory: IPartImportsSatisfiedNotification
{
    [ImportMany(typeof(IHelperOne))]
    private IEnumerable<Lazy<IHelperOne, Dictionary<string, object>>> Helper;

    /// <summary>
    /// reference to the relevant implementaion (HelperOneOriginal or HelperOneCusto)
    /// </summary>
    public IHelperOne Current { get; private set; }

    /// <summary>
    /// looking for all implementations of IHelperOne to find out the one to use
    /// </summary>
    public void OnImportsSatisfied()
    {
        Current = Helper.Count() > 1 ? Helper.First<Lazy<IHelperOne, Dictionary<string, object>>>(s => !s.Metadata.ContainsValue("Original")).Value :
            Helper.First<Lazy<IHelperOne, Dictionary<string, object>>>().Value;
    }

那很好,但是我必須為許多接口類型實現工廠類。 因此,我嘗試對接口類型使用泛型 ,但是隨后出現編譯錯誤(使用.NET Framework 4.6.1):

/// =====================================================================================
/// a version with using generic ==>  compiler-errors !!
/// =====================================================================================
[Export(typeof(HelperTemplateFactory<>))]
public class HelperTemplateFactory<THelperInterface> : IPartImportsSatisfiedNotification
{
    [ImportMany(typeof(THelperInterface))]            // ==> ERROR:       "Attribute argument cannot use type parameters"
    [ImportMany(THelperInterface)]                    // ==> also ERROR:  "Type parameter name is not valid at this point"
    private IEnumerable<Lazy<THelperInterface, Dictionary<string, object>>> Helper;

    ...

是否可以對“ ImportMany”命令使用通用類型?

問題的上下文:

“常規”類“ HelperOneOriginal”是HelperOne的標准版本,可以通過定義子類“ HelperOneCustom”將其覆蓋在Custom-Projects中,該子類通常放置在單獨的VisualStudio-Project中。 這兩個類都有接口“ IHelperOne”。

主程序應使用Custom類(如果已定義),否則應使用Original類。 原始類具有元數據信息“原始”。 因此,“ HelperOneFactory”將查找“ IHelperOne”-接口的所有實現,並采用不帶元數據“ Original”的第一個實現。 如果不存在,則采用原始類。 對存儲在HelperClass中的相關類ist的引用,該成員在“ Current”成員中供主程序使用。

如有必要,可以提供一個小的測試項目。

我建議,我必須寫一個“答案”來標記問題“已解決” =>

a line with only    "[ImportMany]"   is the solution!

感謝Dave M

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM