Here is the singature of the Register method:
IMessanger.Register<TMsg>(object recipient, Action<TMsg> action);
Why do we need the recipient if action holds the reference in its Target property?
When the given action does not use instance members of the class where it was defined then Target is null.
But this happens quite rarely. I mean that it is not a very common way we use event handlers.
I’d like to understand why there is no additonal Register method signature with no recipient parameter? Am I missing something important?
IMessanger.Register<TMsg>(Action<TMsg> action);
You can actually register a recipient for a specific message from anywhere in your application, not just from the class that is the recipient. For example, consider the following scenario:
In the case of the second
Registormethod call, the Target property of the Action will NOT be the same as the recipient parameter. Therefore, to be consistent, it was most likely safer to always require a recipient parameter.Of course, you are correct that this scenario is probably less common than the scenario where you simply pass
thisas the recipient. So in that case, if typingthisbecomes to burdensome for you then you could always define your ownRegisterextension method which simply passes the Target property along to the actualRegistermethod:You can then register for messages like this: