0

这是线程的后续问题:如何使用结构映射将父/子类作为构造函数参数传递?

谢谢菲伯格。真的很有帮助。还有两个问题:

  1. 为什么我们需要 PricingHandlerFactory 构造函数?

  2. 令我沮丧的是,实际上 PricingHandler 并没有直接调用,我们使用反射和 Registry 来查找 PricingHandler。即(并非所有代码都被粘贴。)

public class MessageHandlerRegistry : Registry
{
    public MessageHandlerRegistry()
    {
        Scan(x =>
        {
            x.AssemblyContainingType(typeof(PricingHandler));
            x.ConnectImplementationsToTypesClosing(typeof(IMessageHandler<>));
        });
    }
}

private object QueryHandlerExecute(IMessage message)
{
    var handlerType = typeof(IMessageHandler<>);
    var genericType = handlerType.MakeGenericType(message.GetType());
    var messageHandler = ObjectFactory.GetInstance(genericType);
    return messageHandler.GetType().GetMethod("Execute")
        .Invoke(messageHandler, new object[] { message });
}

的实际声明PricingHandler是:

public class PricingHandler : IMessageHandler<PricingMessage>
{
    public PricingHandler(IPricingFactorsRepository pricingFactorsRepository)
    public object Execute(PricingMessage pricingMsg){}
}

简单地说,我们找到PricingHandlerIMessageHandler<PricingMessage>所以我们不能使用

ObjectFactory.GetInstance<PricingHandler>(); 

找到 PricingHandler 并设置构造函数参数的类型。

那么,在这种情况下,我们如何设置构造函数的参数类型呢?

编辑1。

现在,我正在更新“工厂”类以允许指定命名实例(定价处理程序。)

private object QueryHandlerExecute(IMessage message,string instanceName)
        {
            var handlerType = typeof(IMessageHandler<>);
            var genericType = handlerType.MakeGenericType(message.GetType());
            var messageHandler = string.IsNullOrEmpty(instanceName)
                                     ? ObjectFactory.GetInstance(genericType)
                                     : ObjectFactory.GetNamedInstance(genericType, instanceName);
            return messageHandler.GetType().GetMethod("Execute").Invoke(messageHandler, new object[] { message });
        }
4

0 回答 0