我正在嘗試使用Castle Windsor實現Command,CommandHandler和CommandDispatcher模式,而無需手動要求容器根據Command類型(通常認爲是反模式)來解析CommandHandler。Castle Windsor&Command Pattern
我發現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();
}
謝謝! ;)
謝謝samy,我已經找到這些文章,但不幸的是它仍然無法正常工作。經過幾個小時的戰鬥後,我終於設法使其工作,我會在下面發表一個完整的答案。 無論如何感謝您的幫助! – timurso