-
Notifications
You must be signed in to change notification settings - Fork 1
Publishing events
Shreyas Jejurkar edited this page Aug 23, 2020
·
3 revisions
After creating an event and their corresponding event handler, it's now time to publish those events.
When you register Eventify to DI container, by default it automatically registers InMemoryEventDispatcher
to the container of given IEventPublisher
abstraction. We will see how to publish event with InMemoryEventDispatcher.
Consider the following simple controller code.
using System.Threading.Tasks;
using Eventify;
using Microsoft.AspNetCore.Mvc;
namespace CustomerApp.Controllers
{
[ApiController]
public class CustomerController : ControllerBase
{
private readonly IEventPublisher _eventPublisher;
public CustomerController(IEventPublisher eventPublisher)
{
_eventPublisher = eventPublisher;
}
[HttpPost]
public IActionResult Post(Customer customer)
{
// Save given customer logic
// publishing the CustomerRegisteredEvent with register customer.
_eventPublisher.Publish(new CustomerRegisteredEvent(customer));
return Json(new { Message = "Customer registered successfully." });
}
}
}
As you can see above IEventPublisher
has one method Publish
which takes the only parameter which is nothing but the event which has to be published.
Behind the scenes, the publish method will find all the EventHandlers for the given event and call their Handle
method by passing current event object as an parameter which in this case is customer
object.