【发布时间】:2015-06-19 16:40:16
【问题描述】:
我正在尝试使用 Castle Windsor 实现 Command、CommandHandler 和 CommandDispatcher 模式,而无需手动要求容器根据 Command 类型(通常被认为是反模式)解析 CommandHandler。
我找到了this的旧文章,但是ITypedFactoryComponentSelector的实现已经改变,所以现在它返回一个Func,而不是TypedFactoryComponent。
无论如何,如果有人能阐明这种模式的“正确”实现,我将不胜感激。 当前设置(简化):
public interface ICommand {}
public class CreateUserCommand:ICommand
{
public string Name { get;set; }
}
public interface ICommandHandler<in TCommand> where TCommand: ICommand
{
ICommandResult Execute(TCommand command);
}
public class CreateUserCommandHandler : ICommandHandler<CreateUserCommand>
{
public ICommandResult Execute(CreateUserCommand command)
{
// some logic here
return new CommandResult() {Success = true};
}
}
public interface ICommandDispatcher
{
ICommandResult Submit<TCommand>(TCommand command) where TCommand: ICommand;
}
public class CommandDispatcher : ICommandDispatcher
{
// I DO NOT WANT TO DO THIS:
IWindsorContainer _container;
public CommandDispatcher(IWindsorContainer container)
{
_container = container;
}
public ICommandResult Submit<TCommand>(TCommand command) where TCommand : Commands.ICommand
{
// I DO NOT WANT TO DO THIS TOO:
var handler = _container.Resolve<ICommandHandler<TCommand>>();
if (handler == null)
{
throw new Exception("Command handler not found for command " + typeof(TCommand).ToString());
}
return handler.Execute(command);
}
}
基本上我想要的只是配置容器,使我的 WebAPI 控制器可以依赖 ICommandDispatcher 并简单地执行类似的操作
var result = this.commandDispatcher.Submit(new CreateUserCommand("John Smith"));
if (result.Success){
return Ok();
}
谢谢! ;)
【问题讨论】:
标签: c# dependency-injection inversion-of-control castle-windsor