C# MEF-具有通用接口和;懒惰<;T、 TMetadata>;

C# MEF-具有通用接口和;懒惰<;T、 TMetadata>;,c#,generics,mef,C#,Generics,Mef,我正在使用MEF(特别是)开发一个应用程序,在尝试基于通用接口导入时遇到了一个问题 我有一个界面: public interface IMessageHandler<in T> { void HandleMessage(T message); } 然后,在消费类中,我使用[ImportMany]将这些元素的列表导入到IEnumerable>: 我理解(大致)为什么我会遇到这个异常,问题是我不知道如何避开它。所以,基本上我想做的是: 拥有一组实现IMessageHandler

我正在使用MEF(特别是)开发一个应用程序,在尝试基于通用接口导入时遇到了一个问题

我有一个界面:

public interface IMessageHandler<in T>
{
    void HandleMessage(T message);
}
然后,在消费类中,我使用
[ImportMany]
将这些元素的列表导入到
IEnumerable>

我理解(大致)为什么我会遇到这个异常,问题是我不知道如何避开它。所以,基本上我想做的是:

  • 拥有一组实现
    IMessageHandler
    接口的类
  • 使用MEF在运行时发现它们
  • 将它们导入一个集合,该集合允许我使用它们拥有的任何元数据
  • 能够实例化它们
  • 我知道我可以简单地使
    IMessageHandler
    非泛型,并让
    IMessageHandler.HandleMessage()
    接受
    object
    类型的参数,但我正在寻找一个稍微优雅一点的解决方案


    感谢您提供任何指导。

    如果不使用非通用接口,我看不到更好的方法来实现您想要实现的目标。问题的根源在于接口的定义:

    public interface IMessageHandler<in T>
    
    但这不是:

    IMessageHandler<A> handler = new BHandler();
    
    IMessageHandler也是相关的。希望这有帮助

    Cannot cast the underlying exported value of type 
    'MessageHandlerImplementation (ContractName="IMessageHandler(System.Object)")' 
    to type 'IMessageHandler`1[System.Object]'.
    
    public interface IMessageHandler<in T>
    
    IMessageHandler<B> handler = new AHandler();
    
    IMessageHandler<A> handler = new BHandler();
    
    public IMessageHandler GetHandler<T>()
    {
        Type handlerType = typeof(T);
        return _messageHandlers.FirstOrDefault(x => x.Metadata.MessageType == handlerType);
    }