解决Command Handler与城堡windsor的依赖关系

时间:2015-04-19 20:35:36

标签: c# castle-windsor autofac

我只想在城堡windsor中注册一个通用的命令处理程序,这就是我在ControllerInstaller中所做的:

container.Register(
    Classes
        .FromAssemblyContaining<ProductCommand>()
        .Where(t => t.Name.EndsWith("CommandHandler"))
        .WithService.AllInterfaces()
        .LifestylePerWebRequest());

这是我的ProductCommandHandler类:

public class ProductCommandHandler :  ICommandHandler<CreateProductCommand>
{
}

我的ICommandHandle就是这个:

public interface ICommandHandler<in TCommand> where TCommand : ICommand
{
    ICommandResult Execute(TCommand command);
}

这就是我收到错误的地方:

public class DefaultCommandBus : ICommandBus
{
    public ICommandResult Send<TCommand>(TCommand command) 
        where TCommand : ICommand
    {
        var handler = DependencyResolver.Current
            .GetService<ICommandHandler<TCommand>>();

        if (!((handler != null) && handler != null))
        {
            throw new CommandHandlerNotFoundException(typeof(TCommand));
        }

        return handler.Execute(command);
    }

    public IEnumerable<ValidationResult> Validate<TCommand>(TCommand command) 
        where TCommand : ICommand
    {
        var handler = DependencyResolver.Current
            .GetService<IValidationHandler<TCommand>>();
        if (!((handler != null) && handler != null))
        {
            throw new ValidationHandlerNotFoundException(typeof(TCommand));
        }

        return handler.Validate(command);
    }
}

我用autofac解决了这个问题,如下所示:

builder.RegisterAssemblyTypes(ThisAssembly)
    .AsClosedTypesOf(typeof(ICommandHandler<>)).InstancePerRequest();

但我不知道如何通过Castle Windsor解决它,请帮帮我

1 个答案:

答案 0 :(得分:2)

我有一个与WCF应用程序中相同的机制,其中根据消息类型将调用传递给消息处理程序。我使用它的方式如下:

  • 为邮件处理程序
  • 创建typed factory
  • 使用工厂实例
  • 实例化命令总线(在您的情况下)
  • 为每条消息让工厂解析正确的消息处理程序
  • 调用消息处理程序方法

这很大程度上基于this post by Krzysztof Koźmic,他在这里描述了这个架构。如果您想了解这是如何编码的话,您可以看到my previous answer