پیاده سازی CQRS توسط MediatR - قسمت سوم
نویسنده: معین تاجیک
تاریخ: ۱۳۹۷/۱۱/۱۳ ۱:۳۰
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
Install-Package FluentValidation.AspNetCore
services.AddMvc()
.AddFluentValidation(cfg => cfg.RegisterValidatorsFromAssemblyContaining<Startup>()); public class CreateCustomerCommandValidator : AbstractValidator<CreateCustomerCommand>
{
public CreateCustomerCommandValidator()
{
RuleFor(customer => customer.FirstName).NotEmpty();
RuleFor(customer => customer.LastName).NotEmpty();
}
} Error: Bad Request
{
"LastName": [
"'Last Name' must not be empty."
],
"FirstName": [
"'First Name' must not be empty."
]
}
public class CustomerCreatedEvent : INotification
{
public CustomerCreatedEvent(string firstName, string lastName, DateTime registrationDate)
{
FirstName = firstName;
LastName = lastName;
RegistrationDate = registrationDate;
}
public string FirstName { get; }
public string LastName { get; }
public DateTime RegistrationDate { get; }
} public class CustomerCreatedEmailSenderHandler : INotificationHandler<CustomerCreatedEvent>
{
public Task Handle(CustomerCreatedEvent notification, CancellationToken cancellationToken)
{
// IMessageSender.Send($"Welcome {notification.FirstName} {notification.LastName} !");
return Task.CompletedTask;
}
} public class CustomerCreatedLoggerHandler : INotificationHandler<CustomerCreatedEvent>
{
readonly ILogger<CustomerCreatedLoggerHandler> _logger;
public CustomerCreatedLoggerHandler(ILogger<CustomerCreatedLoggerHandler> logger)
{
_logger = logger;
}
public Task Handle(CustomerCreatedEvent notification, CancellationToken cancellationToken)
{
_logger.LogInformation($"New customer has been created at {notification.RegistrationDate}: {notification.FirstName} {notification.LastName}");
return Task.CompletedTask;
}
} public class CreateCustomerCommandHandler : IRequestHandler<CreateCustomerCommand, CustomerDto>
{
readonly ApplicationDbContext _context;
readonly IMapper _mapper;
readonly IMediator _mediator;
public CreateCustomerCommandHandler(ApplicationDbContext context,
IMapper mapper,
IMediator mediator)
{
_context = context;
_mapper = mapper;
_mediator = mediator;
}
public async Task<CustomerDto> Handle(CreateCustomerCommand createCustomerCommand, CancellationToken cancellationToken)
{
Customer customer = _mapper.Map<Customer>(createCustomerCommand);
await _context.Customers.AddAsync(customer, cancellationToken);
await _context.SaveChangesAsync(cancellationToken);
// Raising Event ...
await _mediator.Publish(new CustomerCreatedEvent(customer.FirstName, customer.LastName, customer.RegistrationDate), cancellationToken);
return _mapper.Map<CustomerDto>(customer);
}
} info: MediatrTutorial.Features.Customer.Events.CustomerCreated.CustomerCreatedLoggerHandler[0]
New customer has been created at 2/1/2019 11:40:48 PM: Moien Tajik