Thursday, 24 April 2014

Have you ever found yourself in a frustrating situation of wiring events across complex winform application wih too many nested controls. If you had worked on some composite frameworks before Prism/CAB etc, you might have wondered if you can get the goodness of simple publish subscribe event model in your winform application. I had implemented a simple EventBroker for such a scenario. My Event Broker is given below (I am using MEF, bu this will hardly make any difference):- [Export] public class MyEventBroker : IMyEventBroker { [ImportingConstructor] public MyEventBroker() { } private readonly ConcurrentDictionary>> _compositeEventHandlers = new ConcurrentDictionary>>(); public void Publish(CompositeEventArguments args) { if (_compositeEventHandlers.ContainsKey(typeof (T))) { _compositeEventHandlers[typeof(T)].ForEach(subscriber=> { if (subscriber != null) subscriber.Invoke(args); }); //TODO : check for null. QUES - Will we need weak references????? } } public void Subscribe(Action handler) { if (!_compositeEventHandlers.ContainsKey(typeof (T))) _compositeEventHandlers[typeof(T)] = new List>(); _compositeEventHandlers[typeof (T)].Add(handler); } public void UnSubscribe(Action handler) { if (_compositeEventHandlers.ContainsKey(typeof (T))) _compositeEventHandlers[typeof (T)].Remove(handler); } } public class CompositeEvent where T : CompositeEventArguments { } public class CompositeEventArguments { }Now to have your custom event, define your event args:- #region Custom Events public class MyCustomEventArgs : CompositeEventArguments{} #endregionThen to publish:- var broker = MefContainer.Instance.Resolve(); broker.Publish(new MyCustomEventArgs());And to subscribe:- var broker = MefContainer.Instance.Resolve(); broker.Subscribe(t=>MyHandler(t));MefContainer is my custom singleton class to expose the composition container. You can use unity, windsor or whatever you like!

2 comments:

  1. Posted for the answer:-

    http://stackoverflow.com/questions/12490462/custom-event-aggregator-in-winforms-mvp-app/23264109#23264109

    ReplyDelete
  2. Took me time to read all the comments, but I really enjoyed the article. It proved to be Very helpful to me and I am sure to all the commenters here! It’s always nice when you can not only be informed, but also entertained! City Index customer review

    ReplyDelete