问题
I´m just trying to wrap my head around CQRS(/ES). I have not done anything serious with CQRS. Probably I´m just missing something very fundamental right now. Currently I´m reading "Exploring CQRS and Event Sourcing". There is one sentence that somehow puzzles my in regards of commands:
"A single recipient processes a command."
I´ve seen this also in the CQRS sample application from Greg Young (FakeBus.cs) where an exception is thrown when more then one command handler is registered for any command type.
For me this is an indication that this is a fundamental principle for CQRS (or Commands?). What is the reason? For me it is somewhat counter intuitive.
Imagine I have two components that need to perform some action in response to a command (it doesn´t matter if I have two instances of the same component or two independent components). Then I would need to create a handler that delegates the command to this components.
In my opinion this is introducing an unnecessary dependency. In terms of CQRS a command is nothing more then a message that is send. I don´t get the reason why there should be only one handler for this message.
Can someone tell me what I am missing here? There is probably a very good reason for this that i just don´t see right now.
Regards
回答1:
I am by no means an expert myself with CQRS, but perhaps I can help shed some light.
"A single recipient processes a command.", What is the reason?
One of the fundamental reasons for this is transactional consistency. A command needs to be handled in one discrete (and isolated) part of the application so that it can be committed in a single transaction. As soon as you start to have multiple handlers, distributing the application beyond a single process (and maintaining transactional consistency) is nearly impossible. So, while you could design that way, it is not recommended.
Hope this helps.
回答2:
Imagine I have two components that need to perform some action in response to a command (it doesn´t matter if I have two instances of the same component or two independent components). Then I would need to create a handler that delegates the command to this components.
That's the responsibility of events.
A command must be handled by one command handler and must change state for a single aggregate root. The aggregate root then raises one or more events indicating that something happened. These events can have multiple listeners that performs desired actions.
For example: you have a PurchaseGift
command. Your command handler load the Purchase
aggregate root and performs the desired operation raising a GiftPurchased
event. You can have one or more listeners to the GiftPurchase
event, one for sending an email to the buyer confirming the operation and another to send the gift by mail.
来源:https://stackoverflow.com/questions/21565202/cqrs-single-command-handler