简体   繁体   English

当接口从MEF中的基本接口派生时如何导出类型

[英]How to export the type when interfaces are derived from base interface in MEF

Below is my scenario. 以下是我的情况。 I am trying to associate the types to the interfaces by using the Export functionality during the initial bootstrap. 我试图在初始引导过程中使用“导出”功能将类型与接口相关联。 However, MEF complains on ImportCardinalityMismatchException.I am fairly new to MEF and I couldn't figure out what's wrong here? 但是,MEF抱怨ImportCardinalityMismatchException.MEF我还很陌生,我不知道这里出了什么问题? The easiest fix is to remove the inheritance. 最简单的解决方法是删除继承。 However, I would like to avoid it. 但是,我想避免这种情况。

   public interface IColourService
    {
        Color GetColourByCountry(string countryName);
    }

    public interface IKnownColourService:IColourService
    {
        bool IsKnownCountry(string countryName);
    }

    public interface IUnKnownColourService:IColourService
    {
       bool IsUnKnownCountry(string countryName);
    }

    [Export(typeof(IColourService))]
    public class ColourService:IColourService
    {
       //implementation
    }

    [Export(typeof(IKnownColourService))]   
    public class KnownColourService:IKnownColourService
    {
       //implementation
    }

    [Export(typeof(IUnKnownColourService))]
    public class UnknownColourService:IUnKnownColourService
    {
       //implementation
    }

Can you not use IColourService as the Type in the Export attribute for all the classes? 您是否不能将IColourService用作所有类的Export属性中的Type?

[Export(typeof(IColourService))]

Then, you can access them with the following property declaration: 然后,您可以使用以下属性声明访问它们:

[ImportMany]
public IEnumerable<IColourService> ColourServices { get; set; }

And add a helper method to get specific types: 并添加一个辅助方法来获取特定类型:

public IEnumerable<T> GetServices<T>()
{
    return ColourServices.OfType<T>().ToList();
}

Hope this helps... 希望这可以帮助...

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

相关问题 调用方法时如何从基中获取派生类类型 - How to obtain the derived class type from base when calling a method 从基接口继承的接口 - Interfaces that inherit from a base interface 实现一个泛型类,其中定义在基本接口类型上,但实现在从该基本接口派生的接口上? - Implement a generic class where the definition is on a base interface type but the implementation is on an interface derived from that base? C#:向下转换通用 object,派生接口到基本接口 - C# : Downcasting Generic object with derived interfaces to the base interface 从基接口集合创建派生接口的通用集合 - Create a generic collection of derived interfaces from a collection of base interfaces 当从基类派生类的对象上调用时,“ this”关键字类型 - “this” keyword type when called on an object of derived class from base class 如何从MEF中的基础结构库导出类? - How to export a class from an infrastructure library in MEF? 从基类调用时,GetType() 会返回派生最多的类型吗? - Will GetType() return the most derived type when called from the base class? 具有从基类派生的其他属性的接口 - Interface With additional property derived from base class 派生自实现接口的基础 class - Derived from a base class that implements an interface
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM