Implement messaging / subscription mechanism in C #

I am prototyping a WPF application with an MVVM pattern. After answering this question, I configured ModelProviderService , which provides models as properties. Consumers of the service are viewing models, i.e. They pull their models out of service, rather than creating them themselves.

 class ModelProviderService { private LoginModel loginModel; public LoginModel LoginModel { get { return loginModel; } set { loginModel = value; } } private ProjectsModel projectsModel; public ProjectsModel ProjectsModel { get { return projectsModel; } set { projectsModel = value; } } public ModelProviderService() { loginModel = new LoginModel(); projectsModel = new ProjectsModel(); } } 

Now, here's what happens:

  • The view mode changes the property, for example. property LoginModel .
  • The viewmodel model returns the model property back to the service by setting its property: modelService.LoginModel.MyProperty = localLoginModel.MyProperty;
  • The service should post: "Hello, my LoginModel model LoginModel just changed."
  • Any other model that has subscribed to this message will pull this modified model from the service.

How can I implement:

  • "broadcast message"?
  • message subscription?
+7
source share
2 answers

You can use MessageBus or EventAggregator to publish messages to subscribers using weak links. Take a look at my implementation (or the NuGet package ),

It can also march message processing for the user interface thread for you (if you need to update the user interface components) by applying HandleOnUIThreadAttribute to the Handle method.

Use in your case will look something like this:

 // The message public class LoginModelChanged { public LoginModelChanged(LoginModel model) { Model = model; } public LoginModel Model { get; private set; } } // Service that publishes messages public class ModelProviderService { private IMessageBus _messageBus; private LoginModel _loginModel; public ModelProviderService(IMessageBus messageBus) { _messageBus = messageBus; } public LoginModel LoginModel { get { return _loginModel; } set { _loginModel = value; _messageBus.Publish(new LoginModelChanged(value)); } } } // Subscribing ViewModel public class SomeViewModel : IHandle<LoginModelChanged> { public SomeViewModel(IMessageBus messageBus) { messageBus.Subscribe(this); } public void Handle(LoginModelChanged message) { // Do something with message.Model } } 

If you want to learn more about internal work and how to implement it; Check out the source code in the GitHub repository . Feel free to use the code as you wish :)

+3
source

If you want to distribute messages within a WPF application, you can upgrade with an EventAggregator prism .

EventAggregator allows view modes to report events poorly without requiring any sender information. This makes it easy to distribute messages through components or modules.

+3
source

All Articles