Skip to content

Defining Event Handlers

Shreyas Jejurkar edited this page Aug 23, 2020 · 3 revisions

Defining Event handler for Events is quite simple with Eventify. The Event Handler class needs to implement the generic IEventHandler<T> interface, where T is a given Event for which you are defining event handler.

The IEventHandler interface only contains one method Handle which takes a given Event as a parameter. And this object holds the information which has passed while publishing event.

Take a look at the following simple example, where we have defined EventHandler for CustomerRegisterEvent, that we created here.

public class CustomerRegisteredEventHandler : IEventHandler<CustomerRegisteredEvent>
{
   private ILogger<CustomerRegisteredEventHandler> _logger;

   public CustomerRegisteredEventHandler(ILogger<CustomerRegisteredEventHandler> logger)
   {
       _logger = logger;
   }

   public Task Handle(CustomerRegisteredEvent event)
   {
        // business logic here
       _logger.Log("Customer has been registed. {customerName}", event.RegisteredCustomer.Name);
   }
}

Right now we are just logging the given customer name, but one can do other stuff as well.

Just to highlight, one event can have as many as an event handler, and those all get called sequentially when the given event gets published.

Clone this wiki locally