Venatu
Venatu

Reputation: 1294

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 to a collection/dictionary containing the events.

Are either of these scenarios possible using C#?

Upvotes: 2

Views: 438

Answers (2)

casperOne
casperOne

Reputation: 74530

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.

Upvotes: 0

afeygin
afeygin

Reputation: 1283

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.

Upvotes: 1

Related Questions