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!
Subscribe to:
Posts (Atom)