I would like to use the messenger of the CommunityToolkit to communicate some view models bewteen them.
If I try to define the dependency injection in this way, I get an exception:
services.AddTransient<IMessenger>();
Because there is no an implementation of the interface.
However, I can register receivers in the constructor of a view model in this way:
WeakReferenceMessenger.Default.Register<MyMessage>(this);
So it seems it is that is a global resource.
So I guess that when a view model send a message, all the receivers get the message, but what happen if only one receiver has to receive the message? I have to check first if the sender is the expected sender.
For example, I have two isolated modules:
public class MainViewModel1
{ ViewModelA _viewModelA; ViewModelB _viewModelB;
public MainViewModel1(ViewModelA paramViewModelA, ViewmodelB paramViewModelB)
{
_viewModelA = paramViewModelA;
_viewModelB = paramViewModelB;
WeakReferenceMessenger.Default.Register<MyMessage>(this);
}
}
public class MainViewModel2 { ViewModelA _viewModelA; ViewModelB _viewModelC;
public MainViewModel2(ViewModelA paramViewModelA, ViewmodelC paramViewModelC)
{
_viewModelA = paramViewModelA;
_viewModelC = paramViewModelC;
WeakReferenceMessenger.Default.Register<MyMessage>(this);
}
}
When the ViewModelA from MainViewModel1 send a message, I only want that is recevied but MainViewModel1, not by MainViewModel2. And When ViewModelA from MainViewModel2 send a message, I only want that mainViewModel2 receives the message.
If I have a general messenger for the whole application, how could handle this case?
Thanks.