使用Ninject查找适当的CommandHandler

时间:2015-11-27 17:03:25

标签: c# generics ninject

我尝试使用与CQRS中使用的命令模式类似的Azure消息队列。

以下是一个示例命令:

public class SetZoneModeCommand : ICommand
{
    public string GatewayId { get; set; }

    public string ReceiverId { get; set; }

    public int ChannelNumber { get; set; }

    public HeatingMode Mode { get; set; }
}

这是它的处理程序

public class SetZoneModeCommandHandler : ICommandHandler<SetZoneModeCommand>
{
    private readonly IDatabaseContext _databaseContext;

    public SetZoneModeCommandHandler(IDatabaseContext databaseContext)
    {
        _databaseContext = databaseContext;
    }

    public RequestStatus Execute(SetZoneModeCommand command)
    {
        if (command == null)
        {
            throw new ArgumentNullException("command");
        }
        var result = new RequestStatus();

        return result;
    }
}

我使用此配置在工作者角色中使用Ninject:

_kernel.Bind(x => x.FromAssembliesMatching("Business.dll")
            .SelectAllClasses()
            .BindDefaultInterface());

这很好,并且正在注入依赖项。

我有一个使用JSON序列化的QueuedCommand对象,它放在Azure Message Queue上:

public class QueuedCommand
{
    public string ClassName { get; set; }

    public object Command { get; set; }

    public DateTime AddedOn { get; set; }

    public int AddedByUserId { get; set; }

    public int RetryCount { get; set; }
}

这是(未经优化的)代码,它试图反序列化QueueCommand并处理它:

var queuedCommand = (QueuedCommand)JsonConvert.DeserializeObject<QueuedCommand>(message.AsString);
            var commandInterface = typeof(ICommand);

            var commandType = (from assembly in AppDomain.CurrentDomain.GetAssemblies()
                from type in assembly.GetTypes()
                where (commandInterface.IsAssignableFrom(type)) && (commandInterface != type)
                      && type.FullName == queuedCommand.ClassName
                select type).FirstOrDefault();

var o = (JObject) queuedCommand.Command;
                var command = (ICommand)o.ToObject(commandType);
                var result = _commandDispatcher.Dispatch(command);

这一切都运行正常,如果我调试,传递给调度程序的命令对象的类型正确,并填充了预期的值。

CommandDispatcher应该为它给出的命令找到CommandHandler的具体实现。我的问题是它不是,我收到一个关于ICommandHandler没有绑定的错误。

如果我将ICommand中的强制转换替换为强制转换为SetZoneModeCommand,那么它会按预期工作。这显然是不可接受的,我认为如果我有一个Object和一个完全限定的类名,那么施放就不会太难。

public interface ICommandDispatcher
{
    /// <summary>
    /// Dispatches a command to its handler
    /// </summary>
    /// <typeparam name="TParameter">Command Type</typeparam>
    /// <param name="command">The command to be passed to the handler</param>
    RequestStatus Dispatch<TParameter>(TParameter command) where TParameter : ICommand;
}

public CommandDispatcher(IKernel kernel)
    {
        if (kernel == null)
        {
            throw new ArgumentNullException("kernel");
        }
        _kernel = kernel;
    }

    public RequestStatus Dispatch<TParameter>(TParameter command) where TParameter : ICommand
    {
        var handler = _kernel.Get<ICommandHandler<TParameter>>();
        return handler.Execute(command);
    }

1 个答案:

答案 0 :(得分:2)

让我用相同的代码编写相同的代码&#34;格式化&#34;:

ICommand command = (ICommand)o.ToObject(commandType);
RequestStatus result = _commandDispatcher.Dispatch<ICommand>(command);

因此,您不必调用ICommandDispatcher.Dispatch<commandType>(command),而是使用类型参数ICommand调用它。您需要使用反射为Dispatch<TParameter>(TParameter command)选择正确的类型参数:

object command = o.ToObject(commandType);

MethodInfo dispatchMethod = GetMethod<ICommand>(c => _commandDispatcher.Dispatch(c))
    .GetGenericMethodDefinition()
    .MakeGenericMethod(commandType);

RequestStatus result = (RequestStatus)dispatchMethod.Invoke(
    _commandDispatcher,
    new object[] { command });


public static MethodInfo GetMethod<T1>(Expression<Action<T1>> methodSelector)
{
    return GetMethodInfo(methodSelector);
}

private static MethodInfo GetMethodInfo(LambdaExpression methodSelector)
{
    if (methodSelector == null)
    {
        throw new ArgumentNullException("methodSelector");
    }
    if (methodSelector.Body.NodeType != ExpressionType.Call)
    {
        throw new ArgumentOutOfRangeException(
            "methodSelector", 
            "Specified expression does is not a method call expression.");
    }

    var callExpression = (MethodCallExpression)methodSelector.Body;
    return callExpression.Method;
}