简体   繁体   English

在MEF中使用通用接口

[英]using generic interfaces in MEF

I am developing an application which is MEF enabled. 我正在开发启用MEF的应用程序。 There is a core library project which works as a glue and implements : 有一个核心库项目可作为胶水并实现:

 CompositionContainer cc = new CompositionContainer(catalog);

 cc.ComposeParts(this);

I have declared all [Import] parts in this core library such below: 我已经在此核心库中声明了所有[Import]部分,如下所示:

 [Import(typeof(IHost))]
        // The imported host form
        public IHost Host
        { get; set; }

   [Import(typeof(ILightStudents<?>))]
   public ILightStudents<?> StudentsAPI  { get; set; }

There in so problem in implementing IHost or other interfaces in other library projects which has [export] attribute, but problem here is that I have declared ILightStudents like this: 在具有[export]属性的其他库项目中实现IHost或其他接口时存在问题,但是这里的问题是我这样声明了ILightStudents:

public interface ILightStudents<T> where T:class
    {
        IEnumerable<T> Students();

        T GetStudent(long id);

    }

But as you saw in previous code, I put '?' 但是,正如您在前面的代码中看到的那样,我输入了“?” mark in import part. 在导入部分标记。 As you know the purpose of generic methods is that you can implement them by which ever class or type you want. 如您所知,通用方法的目的是可以通过所需的任何类或类型来实现它们。 And here I want to implement ILightStudents in other library project with my proper type, but I cant leave [import] part without specifying the type. 在这里,我想用我的正确类型在其他库项目中实现ILightStudents,但是我不能在不指定类型的情况下离开[import]部分。

Would you help me please ? 你能帮我吗?

Edited : 编辑

I almost could solve the problem by using dynamic type binding. 我几乎可以通过使用动态类型绑定来解决该问题。

Use either: 使用以下任一方法:

  • The code in MefContrib or MefContrib中的代码或
  • MEF 2 preview. MEF 2预览。

This feature was added in both - it will be included in .NET 4.5. 两者中均添加了此功能-它将包含在.NET 4.5中。

i copied the answer from another thread here a few days ago: 我几天前从另一个线程复制了答案:

Try 尝试

[Export(typeof(IService<>))]

To get a generic type definition from the typeof operator, you omit type arguments. 要从typeof运算符获取通用类型定义,请省略类型参数。 For types with more than one type parameter, use commas to indicate the "arity" of the type. 对于具有多个类型参数的类型,请使用逗号指示该类型的“ arity”。 For example: 例如:

typeof(List<>)              // not: typeof(List<T>)
typeof(IDictionary<,>)      // not: typeof(IDictionary<K, V>)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM