简体   繁体   English

Structuremap返回开放通用类型的错误实例?

[英]Structuremap returning wrong instance for open generic type?

I am trying to use structuremap with open generic to get instances of a Event handler at run time ,I am using open generic based configuration 我正在尝试使用带有开放式泛型的结构图在运行时获取事件处理程序的实例,我正在使用基于开放式泛型的配置

     // #1 Configuration
         scan.ConnectImplementationsToTypesClosing(typeof(IHandle<>));
// #2 Actual class
      public class EventHandlerClass : 
            IHandle<MyEvent>,
            IHandle<AnotherEvent>,
            IHandle<ThirdEvent>,
        {
             void IHandle<MyEvent>.Handle(MyEvent args)
            {

            }
             void IHandle<AnotherEvent>.Handle(AnotherEvent args)
            {

            }
             void IHandle<ThirdEvent>.Handle(ThirdEvent args)
            {

            }

        }

My code works for cases where I request the depdendency through constructor injection like this works fine. 我的代码适用于需要通过构造函数注入来请求依赖关系的情况,例如这样很好。

public MyClass(IHandle<MyEvent>[] alleventHandlers)
{

}

However in one of my cases , I need to fetch the dependency at runtime . 但是,在我的一种情况下,我需要在运行时获取依赖项。 Below is the code I am using 以下是我正在使用的代码

 // Code
 Type t = typeof(IHandle<>);
 MyEvent m = new MyEvent();
 var generic = t.MakeGenericType(m.GetType());
 dynamic instances = nestedContainer.GetAllInstances(genType) as IEnumerable;

 foreach( dynamic inst in instances)
 {
     inst.Handle(m)

 }

I get the following error. 我收到以下错误。 {"The best overloaded method match for 'MyNameSpace.EventHandlerClass.Handle(MyNameSpace.Events.ThirdEvent)' has some invalid arguments"} {“与'MyNameSpace.EventHandlerClass.Handle(MyNameSpace.Events.ThirdEvent)'最佳的重载方法匹配有一些无效的参数“”}

GetAllInstances somehow seems to return a object of EventHandlerClass with a Handle method expecting ThirdEvent event though I called GetAllInstances with the correct type. 尽管我以正确的类型调用了GetAllInstances,但GetAllInstances似乎以某种方式返回了带有Handle方法的EventHandlerClass对象,该事件期望ThirdEvent事件。

Is this a bug ? 这是一个错误吗? or have i made a mistake in the configuration ? 还是我在配置上犯了一个错误?

The dynamic variable only has access to type methods (typically public, but is based on context). 动态变量只能访问类型方法(通常是公共方法,但基于上下文)。 It does not have access to interface methods that are explicitly implemented. 它无权访问已明确实现的接口方法。 The only way to invoke explicit interface implementations is to cast the object to the interface. 调用显式接口实现的唯一方法是将对象强制转换为接口。

So you have two options, either a) implement the interfaces implicitly as suggested by @Yacoub, or b) use reflection to invoke the method. 因此,您有两个选择,要么a)按照@Yacoub的建议隐式实现接口,要么b)使用反射调用该方法。

foreach(dynamic inst in instances)
{
     Type type = inst.GetType();
     Type interfaceType = type.GetInterfaces().Single(t => t == generic);
     interfaceType.GetMethod("Handle").Invoke(inst, new object[] { m });
}

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

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