نصب پکیج های زیر در پروژه Publisher :
Startup.cs
services.AddAutoMapper(typeof(Startup));
Create Folder (Mapper) -> BasketProfile.cs :
using AutoMapper;
using Basket.Api.Entities;
using EventBus.Messages.Events;
namespace Basket.Api.Mapper
{
public class BasketProfile : Profile
{
public BasketProfile()
{
CreateMap().ReverseMap();
}
}
}
Controller
نکته : یک کلاس به نام IPublishEndpoint داخل MassTransit هستش که کار پابلیش کردن Event رو بر عهده دارد.
#region constructor
private readonly IBasketRepository _basketRepository;
private readonly IPublishEndpoint _publishEndpoint;
private readonly IMapper _mapper;
public BasketController(IBasketRepository basketRepository, IMapper mapper, IPublishEndpoint publishEndpoint)
{
_basketRepository = basketRepository;
_mapper = mapper;
_publishEndpoint = publishEndpoint;
}
#endregion
------------------------
[HttpPost("[action]")]
[ProducesResponseType((int)HttpStatusCode.Accepted)]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
public async Task Checkout([FromBody] BasketCheckout basketCheckout)
{
// get existing basket with total price
var basket = await _basketRepository.GetUserBasket(basketCheckout.UserName);
if (basket == null)
{
return BadRequest();
}
// create BasketCheckoutEvent -- set total price on basketCheckout event message
var eventMessage = _mapper.Map(basketCheckout);
eventMessage.TotalPrice = basket.TotalPrice;
// send checkout event to rabbitmq
await _publishEndpoint.Publish(eventMessage);
return Accepted();
}