这是线索的后续问题:How to pass parent/child class as constructor parameter with structuremap?
谢谢PHeiberg。真有帮助。还有两个问题:
为什么我们需要PricingHandlerFactory构造函数?
让我感到沮丧的是,实际上我没有直接调用PricingHandler,我们使用reflection和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){}
}
简单来说,我们会PricingHandler
找到IMessageHandler<PricingMessage>
。所以我们不能使用
ObjectFactory.GetInstance<PricingHandler>();
找到PricingHandler并设置构造函数参数的类型。
那么,在这种情况下,我们如何设置构造函数参数类型?
EDIT1。
目前,我正在更新'FACTORY'类以允许指定命名实例(pricinghandler。)
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 });
}