Receiving messages from subscriptions: event handlers in receiver microservices In addition to the event subscription logic, you need to implement the internal code for the
integration event handlers (like a callback method). The event handler is where you specify where the
event messages of a certain type will be received and processed.
An event handler first receives an event instance from the event bus. Then it locates the component to
be processed related to that integration event, propagating and persisting the event as a change in
state in the receiver microservice. For example, if a ProductPriceChanged event originates in the
catalog microservice, it is handled in the basket microservice and changes the state in this receiver
basket microservice as well, as shown in the following code.
namespace Microsoft.
eShopOnContainers
.
Services
.
Basket
.
API
.
IntegrationEvents
.
EventHandling
{
public class ProductPriceChangedIntegrationEventHandler :
IIntegrationEventHandler
{
private readonly IBasketRepository _repository;
public ProductPriceChangedIntegrationEventHandler
(
IBasketRepository repository)
{
_repository = repository;
}
public async Task
Handle
(ProductPriceChangedIntegrationEvent @event)
{
var
userIds = await _repository.
GetUsers
();
foreach (
var
id
in userIds)
{
var
basket = await _repository.
GetBasket
(id);
await
UpdatePriceInBasketItems
(@event.
ProductId
, @event.
NewPrice
, basket);
}
}
private async Task
UpdatePriceInBasketItems
(
int
productId,
decimal
newPrice,
CustomerBasket basket)
{
var
itemsToUpdate = basket?.
Items
?.
Where
(x =>
int
.
Parse
(x.
ProductId
) ==
productId).
ToList
();