【问题标题】:How to export the type when interfaces are derived from base interface in MEF接口派生自 MEF 中的基接口时如何导出类型
【发布时间】:2014-04-02 15:53:49
【问题描述】:

以下是我的场景。我试图通过在初始引导期间使用导出功能将类型与接口相关联。但是,MEF 抱怨 ImportCardinalityMismatchException。我对 MEF 还很陌生,我不知道这里出了什么问题?最简单的解决方法是删除继承。但是,我想避免它。

   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
    }

【问题讨论】:

  • 您的问题可能是您拥有三个有效的IColorService 对象,而 MEF 只希望找到一个。我希望通过使用命名导入来解决这个问题。如果我足够强烈地认为这是问题所在,这将是一个答案。
  • @Magus 将检查命名导入。

标签: c# dependency-injection inversion-of-control mef ioc-container


【解决方案1】:

您不能在所有类的导出属性中使用IColourService 作为类型吗?

[Export(typeof(IColourService))]

然后,您可以使用以下属性声明访问它们:

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

并添加辅助方法来获取特定类型:

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

希望这会有所帮助...

【讨论】:

    猜你喜欢
    • 2014-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-23
    • 1970-01-01
    • 2010-12-12
    • 2011-05-07
    • 2010-09-22
    相关资源
    最近更新 更多