I'm looking for a solution to use INotification in MediatR, what I'm trying to do is handling the commits and changes in INotificationHandler, instead of IRequestHandler.
Does it make sense to do so? Product-> AddProduct->ProductWasAdded.
public class AddProductCommandHandler : IRequestHandler<AddProductCommand, Result<ProductTypeId>>
{
private readonly DbContext _writeContext;
private readonly IMediator _mediator;
public AddProductCommandHandler( DbContext writeContext, IMediator mediator )
{
_writeContext = writeContext;
_mediator = mediator;
}
public async Task<Result<ProductTypeId>> Handle( AddProductCommand request, CancellationToken cancellationToken )
{
//Logics ommitedfor bravety
await _mediator.Publish( new ProductWasAddedEvent(product), cancellationToken );
}
}
and in INotificationHandler:
public class ProductWasAddedEvent:INotification
{
public Product Product { get; }
public ProductWasAddedEvent(Product product)
{
Product= product;
}
}
Finally in INotificationHandler:
public class ProductEvents:INotificationHandler<ProductWasAddedEvent>
{
private readonly DbContext _writeContext;
public ProductEvents( DbContext writeContext )
{
_writeContext = writeContext;
}
public async Task Handle( ProductWasAddedEvent notification, CancellationToken cancellationToken )
{
await _writeContext.Products.AddAsync( notification.Product, cancellationToken );
await _writeContext.SaveChangesAsync( cancellationToken );
}
}