目前正在远离处理命令同步并将它们放到消息总线上,以便稍后处理它们但在尝试加载命令时遇到问题而不是输入实际类型而不是输入每个命令
这是我到目前为止所做的,似乎工作正常
命令调度程序
public class CommandDispatcher : ICommandDispatcher
{
private readonly IBus _commandBus;
public CommandDispatcher(IBus commandBus)
{
_commandBus = commandBus;
}
public void Dispatch<TCommand>(TCommand command) where TCommand : ICommand
{
var messageType = typeof(TCommand);
_commandBus.Publish(messageType, command);
}
订阅命令
bus.Subscribe<CommandOne>("key", HandleCommand);
bus.Subscribe<CommandTwo>("key", HandleCommand);
处理讯息
private void HandleCommand<TCommand>(TCommand command) where TCommand : ICommand
{
var handler = _container.Resolve<ICommandHandler<TCommand>>();
handler.Handle(command);
}
我基本上想要按惯例解决我的消息,所以我想要继续前进,所以我不必键入每个命令类型但是有问题让类型回来
var commandAssembly = Assembly.GetAssembly(typeof(ICommand));
var commands = commandAssembly.GetTypes().Where(x => typeof(ICommand).IsAssignableFrom(x));
foreach (var command in commands)
{
bus.Subscribe(command, "key", x =>
{
HandleCommand(x);
});
}
现在x只是一个我无法传递给Handlecommand方法的对象
我使用autofac作为我的容器,easynetq使用我的总线。
答案 0 :(得分:0)
我认为这部分:
private void HandleCommand<TCommand>(TCommand command) where TCommand : ICommand
{
var handler = _container.Resolve<ICommandHandler<TCommand>>();
handler.Handle(command);
}
AutoSubscriber为您完成所有操作,如果您实施IConsume<T>
而不是ICommandHandler<T>
,它们似乎具有相同的目的。
https://github.com/EasyNetQ/EasyNetQ/wiki/Auto-Subscriber
是否有任何特定原因需要单独的ICommandHandler<T>
界面?
另一方面:在您的实现中,您在解析命令处理程序时不会创建单独的“范围”,从而导致处理程序的每个实例(以及任何依赖项)永远存在于“根”范围内。换句话说:内存泄漏:)
如果你仍然想坚持你的实现,我认为做这样的事情会更好:
private void HandleCommand<TCommand>(TCommand command) where TCommand : ICommand
{
using(var scope = _container.BeginLifetimeScope("my-command-scope"))
{
var handler = scope.Resolve<ICommandHandler<TCommand>>();
handler.Handle(command);
}
}
但是,如果您使用AutoSubscriber,这就是AutofacMessageDispatcher将为您做的事情: