Skip to content

Listening to event publishing

Shreyas Jejurkar edited this page Oct 10, 2020 · 1 revision

Background

With the release of Eventify 1.1.0.0, now it's possible to listen to event publishing. This might be useful for logging and exception handling of events.

Before this release, if we want to log the EventId of the current published event then, we need to write a logging statement in each event handler, which is not good practice as the event handler should only concern about handing event and doing some business stuff rather than logging and similar things.

How to listen to event publishing

Listening to event publishing is quite simple, to do so one should implement the IEventPublisherListener interface, that interface contains two methods as following.

    public interface IEventPublisherListener
    {
        /// <summary>
        /// Gets executed before publishing an <see cref="Event"/>
        /// </summary>
        /// <param name="context">Context containing current <see cref="Event"/> information</param>
        void OnEventPublishing(EventPublishingContext context);

        /// <summary>
        /// Gets executed after publishing an <see cref="Event"/>
        /// </summary>
        /// <param name="context">Context containing event execution information</param>
        void OnEventPublished(EventPublishedContext context);
    }

As one might have already guessed, how this works. The method void OnEventPublishing(EventPublishingContext context); gets executed before the current event gets published (I mean before calling its corresponding event handler). The context variable contains some useful information about the event which is currently published. Please check EventPublishingContext type to know the same.

And other method void OnEventPublished(EventPublishedContext context); gets executed after the event has been published, one of the useful information in that, is with IsFaulted property in EventPublishedContext one can know, that event handler is successfully executed or not and there is no exception while doing that. If IsFaulted is true, then it indicates that something has gone wrong while executing event handler and the information about the happened exception is available in EventException property for logging etc.

Clone this wiki locally