Set constructor parameter type for structuremap Registry

家住魔仙堡 提交于 2019-12-11 19:59:38

问题


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:

  1. Why do we need PricingHandlerFactory constructor there?

  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!