问题
This is the follow up question to thread: How to pass parent/child class as constructor parameter with structuremap?
Thanks PHeiberg. Really helps. Got another two questions:
Why do we need PricingHandlerFactory constructor there?
What it frustrate me is that actually PricingHandler is not invoked directly, we are using reflection and Registry to find PricingHandler. i.e.(Not all codes are pasted.)
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 });
}
The actual declaration of PricingHandler
is:
public class PricingHandler : IMessageHandler<PricingMessage>
{
public PricingHandler(IPricingFactorsRepository pricingFactorsRepository)
public object Execute(PricingMessage pricingMsg){}
}
Simply speaking, we find PricingHandler
by IMessageHandler<PricingMessage>
. So we can't use
ObjectFactory.GetInstance<PricingHandler>();
to find PricingHandler and set the type of constructor parameter.
So, in such case, how can we set the constructor parameter type?
Edit1.
For now, I am updating the 'FACTORY' class to allow specifying named instance(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 });
}
来源:https://stackoverflow.com/questions/18821679/set-constructor-parameter-type-for-structuremap-registry