Skip to content

Messaging

Daniel edited this page Sep 5, 2020 · 18 revisions

CodeMonkeys.Messaging

Nuget

The CodeMonkeys.Messaging package contains mechanisms for loosely coupled event communication between different components of your software.

How to work with it?

The central component is the EventAggregator class. This class is responsible for forwarding the events to the correct recipient.

Publishing events

To publish a event you just need to get a instance of the EventAggregator and call its PublishAsync method with a instance which implements the IEvent interface.

Sample:

class SampleEvent : IEvent
{
    public int MyValue { get; set; }
}

static async Task Main()
{
    var aggregator = new EventAggregator();

    var @event = new SampleEvent();
    @event.MyValue = 5;

    await aggregator.PublishAsync(@event);
}

Receiving events

To receive a event the you must implement the ISubscriberOf<TEvent> interface in your component. It is also possible to implement it multiple times. The event you want to send must implement the IEvent interface.

Sample:

class MyReceiver : ISubscriberOf<SampleEvent>
{
    public async Task ReceiveEventAsync(SampleEvent @event)
    {
        Console.WriteLine(@event.MyValue);
    }
}

static async Task Main()
{
    var aggregator = new EventAggregator();
    var receiver = new MyReceiver();

    // You would use 'aggregator.Register(receiver)' when you would like to register all ISubscriberOf<TEvent> implementations on the given class
    aggregator.RegisterTo<SampleEvent>(receiver);

    var @event = new SampleEvent();
    @event.MyValue = 5;

    await aggregator.PublishAsync(@event);
}

Options

No additional options available.

Clone this wiki locally