In practical applications, we can use EventBroker to publish and subscribe to Event Notifications to implement communication between objects. Generally, EventBroker is implemented as the singleton mode. In the project, we use MEF to implement the singleton mode of EventBroker:
public class EventSubscriptionToken{ private EventSubscriptionToken(){} public static EventSubscriptionToken GetNewToken() { var guid = Guid.NewGuid().ToString(); var token = new EventSubscriptionToken {Value = guid}; return token; } public string Value { get; private set; }}public interface IEventBroker{ void Publish<T>(T eventArgs); EventSubscriptionToken Subscribe<T>(Action<T> callback); bool Unsubscribe(EventSubscriptionToken subscriptionToken);}[Export(typeof(IEventBroker))]public class EventBroker : IEventBroker{ private readonly IDictionary<string, object> _callbacksDictionary; [ImportingConstructor] public EventBroker() { _callbacksDictionary = new Dictionary<string, object>(); } public void Publish<T>(T eventArgs) { var callbacksToBeInvoked = _callbacksDictionary.Where(x => x.Value is Action<T>); foreach (var callback in callbacksToBeInvoked) { var actionCallback = (Action<T>)callback.Value; try { actionCallback(eventArgs); } catch (Exception) { } } } public EventSubscriptionToken Subscribe<T>(Action<T> callback) { var token = EventSubscriptionToken.GetNewToken(); _callbacksDictionary.Add(token.Value, callback); return token; } public bool Unsubscribe(EventSubscriptionToken subscriptionToken) { return _callbacksDictionary.Remove(subscriptionToken.Value); }}
Event subscription instance:
_eventBroker.Subscribe<ModelNameChangedEvent>(EntityChangedEventHandler);private void EntityChangedEventHandler(ModelNameChangedEvent obj){ ...}
The subscriber of an event does not need to know which object the event was published. Both parties interact through parameters. The Subscriber performs corresponding operations based on the input parameter object to complete the collaboration between objects.
Event release instance:
_eventBroker.Publish(new ModelNameChangedEvent(entity.ID, entity.SpaceType, entity.Name));
When interaction is required, events are published through parameter objects.