Implementing a message/subscription mechanism in C#

后端 未结 2 1441
傲寒
傲寒 2021-02-06 08:34

I\'m prototyping a WPF application with the MVVM pattern. Following an answer to this question I have set up a ModelProviderService which exposes models as properti

2条回答
  •  悲哀的现实
    2021-02-06 09:21

    You could use a MessageBus or EventAggregator to publish messages to subscribers by using weak references. Take a look at my implementation (or the NuGet packgage).

    It can also marshal the message handling to the UI thread for you (if you need to update UI components) by applying the HandleOnUIThreadAttribute on the Handle method.

    Usage in your case would be something like:

    // 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
    {
        public SomeViewModel(IMessageBus messageBus)
        {
            messageBus.Subscribe(this);
        }
    
        public void Handle(LoginModelChanged message)
        {
            // Do something with message.Model
        }
    }
    

    If you want to know more about the inner workings and how to implement this; Check out the source code in the GitHub repository. Feel free to use the code as you like :)

提交回复
热议问题