Collection of Events
I am using events as a publisher/subscriber pattern in c#. However I dont know at design time how many publishers my program will be using. I would like to dynamically add events to either a class directly, or more plausibly 开发者_C百科to a collection/dictionary containing the events.
Are either of these scenarios possible using C#?
Create a mediator that your publishers publish to and that your subscribers subscribe to. For example:
public class Mediator
{
public static readonly Mediator Current = new Mediator();
public event EventHandler<EventArgs> EventRaised;
public void RaiseEvent(object sender, EventArgs eventArgs)
{
if (EventRaised!=null)
EventRaised(sender, eventArgs);
}
}
public class PublisherEventArgs : EventArgs
{
public string SomeData { get; set; }
}
public class Publisher
{
public void Publish(string data)
{
Mediator.Current.RaiseEvent(this, new PublisherEventArgs() { SomeData = data} );
}
}
public class Subscriber
{
public Subscriber()
{
Mediator.Current.EventRaised += HandlePublishedEvent;
}
private void HandlePublishedEvent(object sender, EventArgs e)
{
if(e is PublisherEventArgs)
{
string data = ((PublisherEventArgs)e).SomeData;
// todo: do something here
}
}
}
Make sure you implement IDisposable on your subscriber (its not in my example) so that it unsubscribes from the Mediator during dispose.
You'll need to disconnect the event from it's source in order to do this. This is commonly done with an event aggregator; it manages clients that want to publish events as well as those that want to subscribe to events. All of this decouples the publishers from the listeners and allows you to do what you are describing.
Prism has an event aggregator out-of-the-box that you can use in the form of the IEventAggregator
interface.
精彩评论