Migrate from ILoggerFactory to ILogger<T> and use Logging Source Generator

This commit is contained in:
Reuben Bond 2023-05-04 16:18:22 -07:00
parent 5397e8d5c8
commit cf02e90aad
15 changed files with 98 additions and 126 deletions

View File

@ -1,4 +1,4 @@
namespace Microsoft.eShopOnContainers.Services.Basket.API.Infrastructure.Repositories; namespace Microsoft.eShopOnContainers.Services.Basket.API.Infrastructure.Repositories;
public class RedisBasketRepository : IBasketRepository public class RedisBasketRepository : IBasketRepository
{ {
@ -6,9 +6,9 @@ public class RedisBasketRepository : IBasketRepository
private readonly ConnectionMultiplexer _redis; private readonly ConnectionMultiplexer _redis;
private readonly IDatabase _database; private readonly IDatabase _database;
public RedisBasketRepository(ILoggerFactory loggerFactory, ConnectionMultiplexer redis) public RedisBasketRepository(ILogger<RedisBasketRepository> logger, ConnectionMultiplexer redis)
{ {
_logger = loggerFactory.CreateLogger<RedisBasketRepository>(); _logger = logger;
_redis = redis; _redis = redis;
_database = redis.GetDatabase(); _database = redis.GetDatabase();
} }

View File

@ -1,5 +1,7 @@
 
using Microsoft.Extensions.Logging.Abstractions;
namespace Basket.FunctionalTests namespace Basket.FunctionalTests
{ {
public class RedisBasketRepositoryTests public class RedisBasketRepositoryTests
@ -48,8 +50,8 @@ namespace Basket.FunctionalTests
RedisBasketRepository BuildBasketRepository(ConnectionMultiplexer connMux) RedisBasketRepository BuildBasketRepository(ConnectionMultiplexer connMux)
{ {
var loggerFactory = new LoggerFactory(); var logger = NullLoggerFactory.Instance.CreateLogger<RedisBasketRepository>();
return new RedisBasketRepository(loggerFactory, connMux); return new RedisBasketRepository(logger, connMux);
} }
List<BasketItem> BuildBasketItems() List<BasketItem> BuildBasketItems()

View File

@ -1,16 +1,16 @@
namespace Microsoft.eShopOnContainers.Services.Ordering.API.Application.DomainEventHandlers; namespace Microsoft.eShopOnContainers.Services.Ordering.API.Application.DomainEventHandlers;
public class OrderCancelledDomainEventHandler public partial class OrderCancelledDomainEventHandler
: INotificationHandler<OrderCancelledDomainEvent> : INotificationHandler<OrderCancelledDomainEvent>
{ {
private readonly IOrderRepository _orderRepository; private readonly IOrderRepository _orderRepository;
private readonly IBuyerRepository _buyerRepository; private readonly IBuyerRepository _buyerRepository;
private readonly ILoggerFactory _logger; private readonly ILogger _logger;
private readonly IOrderingIntegrationEventService _orderingIntegrationEventService; private readonly IOrderingIntegrationEventService _orderingIntegrationEventService;
public OrderCancelledDomainEventHandler( public OrderCancelledDomainEventHandler(
IOrderRepository orderRepository, IOrderRepository orderRepository,
ILoggerFactory logger, ILogger<OrderCancelledDomainEventHandler> logger,
IBuyerRepository buyerRepository, IBuyerRepository buyerRepository,
IOrderingIntegrationEventService orderingIntegrationEventService) IOrderingIntegrationEventService orderingIntegrationEventService)
{ {
@ -20,16 +20,14 @@ public class OrderCancelledDomainEventHandler
_orderingIntegrationEventService = orderingIntegrationEventService; _orderingIntegrationEventService = orderingIntegrationEventService;
} }
public async Task Handle(OrderCancelledDomainEvent orderCancelledDomainEvent, CancellationToken cancellationToken) public async Task Handle(OrderCancelledDomainEvent domainEvent, CancellationToken cancellationToken)
{ {
_logger.CreateLogger<OrderCancelledDomainEvent>() OrderingApiTrace.LogOrderStatusUpdated(_logger, domainEvent.Order.Id, nameof(OrderStatus.Cancelled), OrderStatus.Cancelled.Id);
.LogTrace("Order with Id: {OrderId} has been successfully updated to status {Status} ({Id})",
orderCancelledDomainEvent.Order.Id, nameof(OrderStatus.Cancelled), OrderStatus.Cancelled.Id);
var order = await _orderRepository.GetAsync(orderCancelledDomainEvent.Order.Id); var order = await _orderRepository.GetAsync(domainEvent.Order.Id);
var buyer = await _buyerRepository.FindByIdAsync(order.GetBuyerId.Value.ToString()); var buyer = await _buyerRepository.FindByIdAsync(order.GetBuyerId.Value.ToString());
var orderStatusChangedToCancelledIntegrationEvent = new OrderStatusChangedToCancelledIntegrationEvent(order.Id, order.OrderStatus.Name, buyer.Name); var integrationEvent = new OrderStatusChangedToCancelledIntegrationEvent(order.Id, order.OrderStatus.Name, buyer.Name);
await _orderingIntegrationEventService.AddAndSaveEventAsync(orderStatusChangedToCancelledIntegrationEvent); await _orderingIntegrationEventService.AddAndSaveEventAsync(integrationEvent);
} }
} }

View File

@ -6,11 +6,11 @@ public class OrderShippedDomainEventHandler
private readonly IOrderRepository _orderRepository; private readonly IOrderRepository _orderRepository;
private readonly IBuyerRepository _buyerRepository; private readonly IBuyerRepository _buyerRepository;
private readonly IOrderingIntegrationEventService _orderingIntegrationEventService; private readonly IOrderingIntegrationEventService _orderingIntegrationEventService;
private readonly ILoggerFactory _logger; private readonly ILogger _logger;
public OrderShippedDomainEventHandler( public OrderShippedDomainEventHandler(
IOrderRepository orderRepository, IOrderRepository orderRepository,
ILoggerFactory logger, ILogger<OrderShippedDomainEventHandler> logger,
IBuyerRepository buyerRepository, IBuyerRepository buyerRepository,
IOrderingIntegrationEventService orderingIntegrationEventService) IOrderingIntegrationEventService orderingIntegrationEventService)
{ {
@ -20,16 +20,14 @@ public class OrderShippedDomainEventHandler
_orderingIntegrationEventService = orderingIntegrationEventService; _orderingIntegrationEventService = orderingIntegrationEventService;
} }
public async Task Handle(OrderShippedDomainEvent orderShippedDomainEvent, CancellationToken cancellationToken) public async Task Handle(OrderShippedDomainEvent domainEvent, CancellationToken cancellationToken)
{ {
_logger.CreateLogger<OrderShippedDomainEvent>() OrderingApiTrace.LogOrderStatusUpdated(_logger, domainEvent.Order.Id, nameof(OrderStatus.Shipped), OrderStatus.Shipped.Id);
.LogTrace("Order with Id: {OrderId} has been successfully updated to status {Status} ({Id})",
orderShippedDomainEvent.Order.Id, nameof(OrderStatus.Shipped), OrderStatus.Shipped.Id);
var order = await _orderRepository.GetAsync(orderShippedDomainEvent.Order.Id); var order = await _orderRepository.GetAsync(domainEvent.Order.Id);
var buyer = await _buyerRepository.FindByIdAsync(order.GetBuyerId.Value.ToString()); var buyer = await _buyerRepository.FindByIdAsync(order.GetBuyerId.Value.ToString());
var orderStatusChangedToShippedIntegrationEvent = new OrderStatusChangedToShippedIntegrationEvent(order.Id, order.OrderStatus.Name, buyer.Name); var integrationEvent = new OrderStatusChangedToShippedIntegrationEvent(order.Id, order.OrderStatus.Name, buyer.Name);
await _orderingIntegrationEventService.AddAndSaveEventAsync(orderStatusChangedToShippedIntegrationEvent); await _orderingIntegrationEventService.AddAndSaveEventAsync(integrationEvent);
} }
} }

View File

@ -4,12 +4,13 @@ public class OrderStatusChangedToAwaitingValidationDomainEventHandler
: INotificationHandler<OrderStatusChangedToAwaitingValidationDomainEvent> : INotificationHandler<OrderStatusChangedToAwaitingValidationDomainEvent>
{ {
private readonly IOrderRepository _orderRepository; private readonly IOrderRepository _orderRepository;
private readonly ILoggerFactory _logger; private readonly ILogger _logger;
private readonly IBuyerRepository _buyerRepository; private readonly IBuyerRepository _buyerRepository;
private readonly IOrderingIntegrationEventService _orderingIntegrationEventService; private readonly IOrderingIntegrationEventService _orderingIntegrationEventService;
public OrderStatusChangedToAwaitingValidationDomainEventHandler( public OrderStatusChangedToAwaitingValidationDomainEventHandler(
IOrderRepository orderRepository, ILoggerFactory logger, IOrderRepository orderRepository,
ILogger<OrderStatusChangedToAwaitingValidationDomainEventHandler> logger,
IBuyerRepository buyerRepository, IBuyerRepository buyerRepository,
IOrderingIntegrationEventService orderingIntegrationEventService) IOrderingIntegrationEventService orderingIntegrationEventService)
{ {
@ -19,21 +20,17 @@ public class OrderStatusChangedToAwaitingValidationDomainEventHandler
_orderingIntegrationEventService = orderingIntegrationEventService; _orderingIntegrationEventService = orderingIntegrationEventService;
} }
public async Task Handle(OrderStatusChangedToAwaitingValidationDomainEvent orderStatusChangedToAwaitingValidationDomainEvent, CancellationToken cancellationToken) public async Task Handle(OrderStatusChangedToAwaitingValidationDomainEvent domainEvent, CancellationToken cancellationToken)
{ {
_logger.CreateLogger<OrderStatusChangedToAwaitingValidationDomainEvent>() OrderingApiTrace.LogOrderStatusUpdated(_logger, domainEvent.OrderId, nameof(OrderStatus.AwaitingValidation), OrderStatus.AwaitingValidation.Id);
.LogTrace("Order with Id: {OrderId} has been successfully updated to status {Status} ({Id})",
orderStatusChangedToAwaitingValidationDomainEvent.OrderId, nameof(OrderStatus.AwaitingValidation), OrderStatus.AwaitingValidation.Id);
var order = await _orderRepository.GetAsync(orderStatusChangedToAwaitingValidationDomainEvent.OrderId);
var order = await _orderRepository.GetAsync(domainEvent.OrderId);
var buyer = await _buyerRepository.FindByIdAsync(order.GetBuyerId.Value.ToString()); var buyer = await _buyerRepository.FindByIdAsync(order.GetBuyerId.Value.ToString());
var orderStockList = orderStatusChangedToAwaitingValidationDomainEvent.OrderItems var orderStockList = domainEvent.OrderItems
.Select(orderItem => new OrderStockItem(orderItem.ProductId, orderItem.GetUnits())); .Select(orderItem => new OrderStockItem(orderItem.ProductId, orderItem.GetUnits()));
var orderStatusChangedToAwaitingValidationIntegrationEvent = new OrderStatusChangedToAwaitingValidationIntegrationEvent( var integrationEvent = new OrderStatusChangedToAwaitingValidationIntegrationEvent(order.Id, order.OrderStatus.Name, buyer.Name, orderStockList);
order.Id, order.OrderStatus.Name, buyer.Name, orderStockList); await _orderingIntegrationEventService.AddAndSaveEventAsync(integrationEvent);
await _orderingIntegrationEventService.AddAndSaveEventAsync(orderStatusChangedToAwaitingValidationIntegrationEvent);
} }
} }

View File

@ -1,17 +1,15 @@
namespace Microsoft.eShopOnContainers.Services.Ordering.API.Application.DomainEventHandlers; namespace Microsoft.eShopOnContainers.Services.Ordering.API.Application.DomainEventHandlers;
public class OrderStatusChangedToPaidDomainEventHandler public class OrderStatusChangedToPaidDomainEventHandler : INotificationHandler<OrderStatusChangedToPaidDomainEvent>
: INotificationHandler<OrderStatusChangedToPaidDomainEvent>
{ {
private readonly IOrderRepository _orderRepository; private readonly IOrderRepository _orderRepository;
private readonly ILoggerFactory _logger; private readonly ILogger _logger;
private readonly IBuyerRepository _buyerRepository; private readonly IBuyerRepository _buyerRepository;
private readonly IOrderingIntegrationEventService _orderingIntegrationEventService; private readonly IOrderingIntegrationEventService _orderingIntegrationEventService;
public OrderStatusChangedToPaidDomainEventHandler( public OrderStatusChangedToPaidDomainEventHandler(
IOrderRepository orderRepository, IOrderRepository orderRepository,
ILoggerFactory logger, ILogger<OrderStatusChangedToPaidDomainEventHandler> logger,
IBuyerRepository buyerRepository, IBuyerRepository buyerRepository,
IOrderingIntegrationEventService orderingIntegrationEventService) IOrderingIntegrationEventService orderingIntegrationEventService)
{ {
@ -21,24 +19,22 @@ public class OrderStatusChangedToPaidDomainEventHandler
_orderingIntegrationEventService = orderingIntegrationEventService ?? throw new ArgumentNullException(nameof(orderingIntegrationEventService)); _orderingIntegrationEventService = orderingIntegrationEventService ?? throw new ArgumentNullException(nameof(orderingIntegrationEventService));
} }
public async Task Handle(OrderStatusChangedToPaidDomainEvent orderStatusChangedToPaidDomainEvent, CancellationToken cancellationToken) public async Task Handle(OrderStatusChangedToPaidDomainEvent domainEvent, CancellationToken cancellationToken)
{ {
_logger.CreateLogger<OrderStatusChangedToPaidDomainEventHandler>() OrderingApiTrace.LogOrderStatusUpdated(_logger, domainEvent.OrderId, nameof(OrderStatus.Paid), OrderStatus.Paid.Id);
.LogInformation("Order with Id: {OrderId} has been successfully updated to status {Status} ({Id})",
orderStatusChangedToPaidDomainEvent.OrderId, nameof(OrderStatus.Paid), OrderStatus.Paid.Id);
var order = await _orderRepository.GetAsync(orderStatusChangedToPaidDomainEvent.OrderId); var order = await _orderRepository.GetAsync(domainEvent.OrderId);
var buyer = await _buyerRepository.FindByIdAsync(order.GetBuyerId.Value.ToString()); var buyer = await _buyerRepository.FindByIdAsync(order.GetBuyerId.Value.ToString());
var orderStockList = orderStatusChangedToPaidDomainEvent.OrderItems var orderStockList = domainEvent.OrderItems
.Select(orderItem => new OrderStockItem(orderItem.ProductId, orderItem.GetUnits())); .Select(orderItem => new OrderStockItem(orderItem.ProductId, orderItem.GetUnits()));
var orderStatusChangedToPaidIntegrationEvent = new OrderStatusChangedToPaidIntegrationEvent( var integrationEvent = new OrderStatusChangedToPaidIntegrationEvent(
orderStatusChangedToPaidDomainEvent.OrderId, domainEvent.OrderId,
order.OrderStatus.Name, order.OrderStatus.Name,
buyer.Name, buyer.Name,
orderStockList); orderStockList);
await _orderingIntegrationEventService.AddAndSaveEventAsync(orderStatusChangedToPaidIntegrationEvent); await _orderingIntegrationEventService.AddAndSaveEventAsync(integrationEvent);
} }
} }

View File

@ -5,13 +5,13 @@ public class OrderStatusChangedToStockConfirmedDomainEventHandler
{ {
private readonly IOrderRepository _orderRepository; private readonly IOrderRepository _orderRepository;
private readonly IBuyerRepository _buyerRepository; private readonly IBuyerRepository _buyerRepository;
private readonly ILoggerFactory _logger; private readonly ILogger _logger;
private readonly IOrderingIntegrationEventService _orderingIntegrationEventService; private readonly IOrderingIntegrationEventService _orderingIntegrationEventService;
public OrderStatusChangedToStockConfirmedDomainEventHandler( public OrderStatusChangedToStockConfirmedDomainEventHandler(
IOrderRepository orderRepository, IOrderRepository orderRepository,
IBuyerRepository buyerRepository, IBuyerRepository buyerRepository,
ILoggerFactory logger, ILogger<OrderStatusChangedToStockConfirmedDomainEventHandler> logger,
IOrderingIntegrationEventService orderingIntegrationEventService) IOrderingIntegrationEventService orderingIntegrationEventService)
{ {
_orderRepository = orderRepository ?? throw new ArgumentNullException(nameof(orderRepository)); _orderRepository = orderRepository ?? throw new ArgumentNullException(nameof(orderRepository));
@ -20,16 +20,14 @@ public class OrderStatusChangedToStockConfirmedDomainEventHandler
_orderingIntegrationEventService = orderingIntegrationEventService; _orderingIntegrationEventService = orderingIntegrationEventService;
} }
public async Task Handle(OrderStatusChangedToStockConfirmedDomainEvent orderStatusChangedToStockConfirmedDomainEvent, CancellationToken cancellationToken) public async Task Handle(OrderStatusChangedToStockConfirmedDomainEvent domainEvent, CancellationToken cancellationToken)
{ {
_logger.CreateLogger<OrderStatusChangedToStockConfirmedDomainEventHandler>() OrderingApiTrace.LogOrderStatusUpdated(_logger, domainEvent.OrderId, nameof(OrderStatus.StockConfirmed), OrderStatus.StockConfirmed.Id);
.LogTrace("Order with Id: {OrderId} has been successfully updated to status {Status} ({Id})",
orderStatusChangedToStockConfirmedDomainEvent.OrderId, nameof(OrderStatus.StockConfirmed), OrderStatus.StockConfirmed.Id);
var order = await _orderRepository.GetAsync(orderStatusChangedToStockConfirmedDomainEvent.OrderId); var order = await _orderRepository.GetAsync(domainEvent.OrderId);
var buyer = await _buyerRepository.FindByIdAsync(order.GetBuyerId.Value.ToString()); var buyer = await _buyerRepository.FindByIdAsync(order.GetBuyerId.Value.ToString());
var orderStatusChangedToStockConfirmedIntegrationEvent = new OrderStatusChangedToStockConfirmedIntegrationEvent(order.Id, order.OrderStatus.Name, buyer.Name); var integrationEvent = new OrderStatusChangedToStockConfirmedIntegrationEvent(order.Id, order.OrderStatus.Name, buyer.Name);
await _orderingIntegrationEventService.AddAndSaveEventAsync(orderStatusChangedToStockConfirmedIntegrationEvent); await _orderingIntegrationEventService.AddAndSaveEventAsync(integrationEvent);
} }
} }

View File

@ -1,15 +0,0 @@
namespace Microsoft.eShopOnContainers.Services.Ordering.API.Application.DomainEventHandlers;
public class SendEmailToCustomerWhenOrderStartedDomainEventHandler
//: IAsyncNotificationHandler<OrderStartedDomainEvent>
{
public SendEmailToCustomerWhenOrderStartedDomainEventHandler()
{
}
//public async Task Handle(OrderStartedDomainEvent orderNotification)
//{
// //TBD - Send email logic
//}
}

View File

@ -1,13 +1,13 @@
namespace Microsoft.eShopOnContainers.Services.Ordering.API.Application.DomainEventHandlers; namespace Microsoft.eShopOnContainers.Services.Ordering.API.Application.DomainEventHandlers;
public class UpdateOrderWhenBuyerAndPaymentMethodVerifiedDomainEventHandler public class UpdateOrderWhenBuyerAndPaymentMethodVerifiedDomainEventHandler : INotificationHandler<BuyerAndPaymentMethodVerifiedDomainEvent>
: INotificationHandler<BuyerAndPaymentMethodVerifiedDomainEvent>
{ {
private readonly IOrderRepository _orderRepository; private readonly IOrderRepository _orderRepository;
private readonly ILoggerFactory _logger; private readonly ILogger _logger;
public UpdateOrderWhenBuyerAndPaymentMethodVerifiedDomainEventHandler( public UpdateOrderWhenBuyerAndPaymentMethodVerifiedDomainEventHandler(
IOrderRepository orderRepository, ILoggerFactory logger) IOrderRepository orderRepository,
ILogger<UpdateOrderWhenBuyerAndPaymentMethodVerifiedDomainEventHandler> logger)
{ {
_orderRepository = orderRepository ?? throw new ArgumentNullException(nameof(orderRepository)); _orderRepository = orderRepository ?? throw new ArgumentNullException(nameof(orderRepository));
_logger = logger ?? throw new ArgumentNullException(nameof(logger)); _logger = logger ?? throw new ArgumentNullException(nameof(logger));
@ -16,14 +16,11 @@ public class UpdateOrderWhenBuyerAndPaymentMethodVerifiedDomainEventHandler
// Domain Logic comment: // Domain Logic comment:
// When the Buyer and Buyer's payment method have been created or verified that they existed, // When the Buyer and Buyer's payment method have been created or verified that they existed,
// then we can update the original Order with the BuyerId and PaymentId (foreign keys) // then we can update the original Order with the BuyerId and PaymentId (foreign keys)
public async Task Handle(BuyerAndPaymentMethodVerifiedDomainEvent buyerPaymentMethodVerifiedEvent, CancellationToken cancellationToken) public async Task Handle(BuyerAndPaymentMethodVerifiedDomainEvent domainEvent, CancellationToken cancellationToken)
{ {
var orderToUpdate = await _orderRepository.GetAsync(buyerPaymentMethodVerifiedEvent.OrderId); var orderToUpdate = await _orderRepository.GetAsync(domainEvent.OrderId);
orderToUpdate.SetBuyerId(buyerPaymentMethodVerifiedEvent.Buyer.Id); orderToUpdate.SetBuyerId(domainEvent.Buyer.Id);
orderToUpdate.SetPaymentId(buyerPaymentMethodVerifiedEvent.Payment.Id); orderToUpdate.SetPaymentId(domainEvent.Payment.Id);
OrderingApiTrace.LogOrderPaymentMethodUpdated(_logger, domainEvent.OrderId, nameof(domainEvent.Payment), domainEvent.Payment.Id);
_logger.CreateLogger<UpdateOrderWhenBuyerAndPaymentMethodVerifiedDomainEventHandler>()
.LogTrace("Order with Id: {OrderId} has been successfully updated with a payment method {PaymentMethod} ({Id})",
buyerPaymentMethodVerifiedEvent.OrderId, nameof(buyerPaymentMethodVerifiedEvent.Payment), buyerPaymentMethodVerifiedEvent.Payment.Id);
} }
} }

View File

@ -3,53 +3,48 @@
public class ValidateOrAddBuyerAggregateWhenOrderStartedDomainEventHandler public class ValidateOrAddBuyerAggregateWhenOrderStartedDomainEventHandler
: INotificationHandler<OrderStartedDomainEvent> : INotificationHandler<OrderStartedDomainEvent>
{ {
private readonly ILoggerFactory _logger; private readonly ILogger _logger;
private readonly IBuyerRepository _buyerRepository; private readonly IBuyerRepository _buyerRepository;
private readonly IIdentityService _identityService;
private readonly IOrderingIntegrationEventService _orderingIntegrationEventService; private readonly IOrderingIntegrationEventService _orderingIntegrationEventService;
public ValidateOrAddBuyerAggregateWhenOrderStartedDomainEventHandler( public ValidateOrAddBuyerAggregateWhenOrderStartedDomainEventHandler(
ILoggerFactory logger, ILogger<ValidateOrAddBuyerAggregateWhenOrderStartedDomainEventHandler> logger,
IBuyerRepository buyerRepository, IBuyerRepository buyerRepository,
IIdentityService identityService,
IOrderingIntegrationEventService orderingIntegrationEventService) IOrderingIntegrationEventService orderingIntegrationEventService)
{ {
_buyerRepository = buyerRepository ?? throw new ArgumentNullException(nameof(buyerRepository)); _buyerRepository = buyerRepository ?? throw new ArgumentNullException(nameof(buyerRepository));
_identityService = identityService ?? throw new ArgumentNullException(nameof(identityService));
_orderingIntegrationEventService = orderingIntegrationEventService ?? throw new ArgumentNullException(nameof(orderingIntegrationEventService)); _orderingIntegrationEventService = orderingIntegrationEventService ?? throw new ArgumentNullException(nameof(orderingIntegrationEventService));
_logger = logger ?? throw new ArgumentNullException(nameof(logger)); _logger = logger ?? throw new ArgumentNullException(nameof(logger));
} }
public async Task Handle(OrderStartedDomainEvent orderStartedEvent, CancellationToken cancellationToken) public async Task Handle(OrderStartedDomainEvent domainEvent, CancellationToken cancellationToken)
{ {
var cardTypeId = orderStartedEvent.CardTypeId != 0 ? orderStartedEvent.CardTypeId : 1; var cardTypeId = domainEvent.CardTypeId != 0 ? domainEvent.CardTypeId : 1;
var buyer = await _buyerRepository.FindAsync(orderStartedEvent.UserId); var buyer = await _buyerRepository.FindAsync(domainEvent.UserId);
var buyerOriginallyExisted = buyer == null ? false : true; var buyerExisted = buyer is not null;
if (!buyerOriginallyExisted) if (!buyerExisted)
{ {
buyer = new Buyer(orderStartedEvent.UserId, orderStartedEvent.UserName); buyer = new Buyer(domainEvent.UserId, domainEvent.UserName);
} }
buyer.VerifyOrAddPaymentMethod(cardTypeId, buyer.VerifyOrAddPaymentMethod(cardTypeId,
$"Payment Method on {DateTime.UtcNow}", $"Payment Method on {DateTime.UtcNow}",
orderStartedEvent.CardNumber, domainEvent.CardNumber,
orderStartedEvent.CardSecurityNumber, domainEvent.CardSecurityNumber,
orderStartedEvent.CardHolderName, domainEvent.CardHolderName,
orderStartedEvent.CardExpiration, domainEvent.CardExpiration,
orderStartedEvent.Order.Id); domainEvent.Order.Id);
var buyerUpdated = buyerOriginallyExisted ? var buyerUpdated = buyerExisted ?
_buyerRepository.Update(buyer) : _buyerRepository.Update(buyer) :
_buyerRepository.Add(buyer); _buyerRepository.Add(buyer);
await _buyerRepository.UnitOfWork await _buyerRepository.UnitOfWork
.SaveEntitiesAsync(cancellationToken); .SaveEntitiesAsync(cancellationToken);
var orderStatusChangedToSubmittedIntegrationEvent = new OrderStatusChangedToSubmittedIntegrationEvent(orderStartedEvent.Order.Id, orderStartedEvent.Order.OrderStatus.Name, buyer.Name); var integrationEvent = new OrderStatusChangedToSubmittedIntegrationEvent(domainEvent.Order.Id, domainEvent.Order.OrderStatus.Name, buyer.Name);
await _orderingIntegrationEventService.AddAndSaveEventAsync(orderStatusChangedToSubmittedIntegrationEvent); await _orderingIntegrationEventService.AddAndSaveEventAsync(integrationEvent);
_logger.CreateLogger<ValidateOrAddBuyerAggregateWhenOrderStartedDomainEventHandler>() OrderingApiTrace.LogOrderBuyerAndPaymentValidatedOrUpdated(_logger, buyerUpdated.Id, domainEvent.Order.Id);
.LogTrace("Buyer {BuyerId} and related payment method were validated or updated for orderId: {OrderId}.",
buyerUpdated.Id, orderStartedEvent.Order.Id);
} }
} }

View File

@ -0,0 +1,13 @@
namespace Microsoft.eShopOnContainers.Services.Ordering.API.Application.DomainEventHandlers;
internal static partial class OrderingApiTrace
{
[LoggerMessage(EventId = 1, EventName = "OrderStatusUpdated", Level = LogLevel.Trace, Message = "Order with Id: {OrderId} has been successfully updated to status {Status} ({Id})")]
public static partial void LogOrderStatusUpdated(ILogger logger, int orderId, string status, int id);
[LoggerMessage(EventId = 2, EventName = "PaymentMethodUpdated", Level = LogLevel.Trace, Message = "Order with Id: {OrderId} has been successfully updated with a payment method {PaymentMethod} ({Id})")]
public static partial void LogOrderPaymentMethodUpdated(ILogger logger, int orderId, string paymentMethod, int id);
[LoggerMessage(EventId = 3, EventName = "BuyerAndPaymentValidatedOrUpdated", Level = LogLevel.Trace, Message = "Buyer {BuyerId} and related payment method were validated or updated for order Id: {OrderId}.")]
public static partial void LogOrderBuyerAndPaymentValidatedOrUpdated(ILogger logger, int buyerId, int orderId);
}

View File

@ -1,7 +1,6 @@
namespace Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.BuyerAggregate; namespace Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.BuyerAggregate;
public class PaymentMethod public class PaymentMethod : Entity
: Entity
{ {
private string _alias; private string _alias;
private string _cardNumber; private string _cardNumber;
@ -12,12 +11,10 @@ public class PaymentMethod
private int _cardTypeId; private int _cardTypeId;
public CardType CardType { get; private set; } public CardType CardType { get; private set; }
protected PaymentMethod() { } protected PaymentMethod() { }
public PaymentMethod(int cardTypeId, string alias, string cardNumber, string securityNumber, string cardHolderName, DateTime expiration) public PaymentMethod(int cardTypeId, string alias, string cardNumber, string securityNumber, string cardHolderName, DateTime expiration)
{ {
_cardNumber = !string.IsNullOrWhiteSpace(cardNumber) ? cardNumber : throw new OrderingDomainException(nameof(cardNumber)); _cardNumber = !string.IsNullOrWhiteSpace(cardNumber) ? cardNumber : throw new OrderingDomainException(nameof(cardNumber));
_securityNumber = !string.IsNullOrWhiteSpace(securityNumber) ? securityNumber : throw new OrderingDomainException(nameof(securityNumber)); _securityNumber = !string.IsNullOrWhiteSpace(securityNumber) ? securityNumber : throw new OrderingDomainException(nameof(securityNumber));
_cardHolderName = !string.IsNullOrWhiteSpace(cardHolderName) ? cardHolderName : throw new OrderingDomainException(nameof(cardHolderName)); _cardHolderName = !string.IsNullOrWhiteSpace(cardHolderName) ? cardHolderName : throw new OrderingDomainException(nameof(cardHolderName));

View File

@ -8,7 +8,6 @@ public class Startup
Configuration = configuration; Configuration = configuration;
} }
public IServiceProvider ConfigureServices(IServiceCollection services) public IServiceProvider ConfigureServices(IServiceCollection services)
{ {
services services
@ -29,13 +28,13 @@ public class Startup
return services.BuildServiceProvider(); return services.BuildServiceProvider();
} }
public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) public void Configure(IApplicationBuilder app, ILogger<Startup> logger)
{ {
var pathBase = Configuration["PATH_BASE"]; var pathBase = Configuration["PATH_BASE"];
if (!string.IsNullOrEmpty(pathBase)) if (!string.IsNullOrEmpty(pathBase))
{ {
loggerFactory.CreateLogger("init").LogDebug("Using PATH BASE '{PathBase}'", pathBase); logger.LogDebug("Using PATH BASE '{PathBase}'", pathBase);
app.UsePathBase(pathBase); app.UsePathBase(pathBase);
} }

View File

@ -61,14 +61,13 @@ app.Use(next => context =>
}); });
// Seed Data // Seed Data
var loggerFactory = app.Services.GetRequiredService<ILoggerFactory>(); WebContextSeed.Seed(app, app.Environment, app.Services.GetRequiredService<ILogger<WebContextSeed>>());
WebContextSeed.Seed(app, app.Environment, loggerFactory);
var pathBase = app.Configuration["PATH_BASE"]; var pathBase = app.Configuration["PATH_BASE"];
if (!string.IsNullOrEmpty(pathBase)) if (!string.IsNullOrEmpty(pathBase))
{ {
loggerFactory.CreateLogger<Program>().LogDebug("Using PATH_BASE '{PathBase}'", pathBase); app.Services.GetRequiredService<ILogger<WebContextSeed>>().LogDebug("Using PATH_BASE '{PathBase}'", pathBase);
app.UsePathBase(pathBase); app.UsePathBase(pathBase);
} }

View File

@ -4,10 +4,8 @@ using Microsoft.Extensions.Logging;
public class WebContextSeed public class WebContextSeed
{ {
public static void Seed(IApplicationBuilder applicationBuilder, IWebHostEnvironment env, ILoggerFactory loggerFactory) public static void Seed(IApplicationBuilder applicationBuilder, IWebHostEnvironment env, ILogger<WebContextSeed> logger)
{ {
var log = loggerFactory.CreateLogger<WebContextSeed>();
var settings = applicationBuilder var settings = applicationBuilder
.ApplicationServices.GetRequiredService<IOptions<AppSettings>>().Value; .ApplicationServices.GetRequiredService<IOptions<AppSettings>>().Value;
@ -17,18 +15,18 @@ public class WebContextSeed
if (useCustomizationData) if (useCustomizationData)
{ {
GetPreconfiguredImages(contentRootPath, webroot, log); GetPreconfiguredImages(contentRootPath, webroot, logger);
} }
} }
static void GetPreconfiguredImages(string contentRootPath, string webroot, ILogger log) static void GetPreconfiguredImages(string contentRootPath, string webroot, ILogger logger)
{ {
try try
{ {
string imagesZipFile = Path.Combine(contentRootPath, "Setup", "images.zip"); string imagesZipFile = Path.Combine(contentRootPath, "Setup", "images.zip");
if (!File.Exists(imagesZipFile)) if (!File.Exists(imagesZipFile))
{ {
log.LogError("Zip file '{ZipFileName}' does not exists.", imagesZipFile); logger.LogError("Zip file '{ZipFileName}' does not exists.", imagesZipFile);
return; return;
} }
@ -53,13 +51,13 @@ public class WebContextSeed
} }
else else
{ {
log.LogWarning("Skipped file '{FileName}' in zipfile '{ZipFileName}'", entry.Name, imagesZipFile); logger.LogWarning("Skipped file '{FileName}' in zipfile '{ZipFileName}'", entry.Name, imagesZipFile);
} }
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
log.LogError(ex, "ERROR in GetPreconfiguredImages: {Message}", ex.Message); logger.LogError(ex, "ERROR in GetPreconfiguredImages: {Message}", ex.Message);
} }
} }
} }