پیاده سازی CQRS توسط MediatR - قسمت چهارم
نویسنده: معین تاجیک
تاریخ: ۱۳۹۷/۱۱/۲۲ ۱۴:۵۰
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
public class SomeClass
{
private readonly ILogger _logger;
public SomeClass(ILogger logger)
{
_logger = logger;
}
public void SomeMethod()
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
// TODO: Do some work here
stopwatch.Stop();
if (stopwatch.ElapsedMilliseconds > TimeSpan.FromSeconds(5).Milliseconds)
{
// This method has taken a long time, So we log that to check it later.
_logger.LogWarning($"SomeClass.SomeMethod has taken {stopwatch.ElapsedMilliseconds} to run completely !");
}
}
} public class RequestPerformanceBehavior<TRequest, TResponse> :
IPipelineBehavior<TRequest, TResponse>
{
private readonly ILogger<RequestPerformanceBehavior<TRequest, TResponse>> _logger;
public RequestPerformanceBehavior(ILogger<RequestPerformanceBehavior<TRequest, TResponse>> logger)
{
_logger = logger;
}
public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
TResponse response = await next();
stopwatch.Stop();
if (stopwatch.ElapsedMilliseconds > TimeSpan.FromSeconds(5).Milliseconds)
{
// This method has taken a long time, So we log that to check it later.
_logger.LogWarning($"{request} has taken {stopwatch.ElapsedMilliseconds} to run completely !");
}
return response;
}
} services.AddScoped(typeof(IPipelineBehavior<,>), typeof(RequestPerformanceBehavior<,>));
public class GetCustomerByIdQueryHandler : IRequestHandler<GetCustomerByIdQuery, CustomerDto>
{
private readonly ApplicationDbContext _context;
private readonly IMapper _mapper;
public GetCustomerByIdQueryHandler(ApplicationDbContext context, IMapper mapper)
{
_context = context;
_mapper = mapper;
}
public async Task<CustomerDto> Handle(GetCustomerByIdQuery request, CancellationToken cancellationToken)
{
Customer customer = await _context.Customers
.FindAsync(request.CustomerId);
if (customer == null)
{
throw new RestException(HttpStatusCode.NotFound, "Customer with given ID is not found.");
}
// For testing PerformanceBehavior
await Task.Delay(5000, cancellationToken);
return _mapper.Map<CustomerDto>(customer);
}
}
public class TransactionBehavior<TRequest, TResponse> :
IPipelineBehavior<TRequest, TResponse>
{
public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
{
var transactionOptions = new TransactionOptions
{
IsolationLevel = IsolationLevel.ReadCommitted,
Timeout = TransactionManager.MaximumTimeout
};
using (var transaction = new TransactionScope(TransactionScopeOption.Required, transactionOptions,
TransactionScopeAsyncFlowOption.Enabled))
{
TResponse response = await next();
transaction.Complete();
return response;
}
}
} services.AddScoped(typeof(IPipelineBehavior<,>), typeof(TransactionBehavior<,>));
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)
{
Domain.Customer customer = _mapper.Map<Domain.Customer>(createCustomerCommand);
await _context.Customers.AddAsync(customer, cancellationToken);
await _context.SaveChangesAsync(cancellationToken);
throw new Exception("======= MY CUSTOM EXCEPTION =======");
// Raising Event ...
await _mediator.Publish(new CustomerCreatedEvent(customer.FirstName, customer.LastName, customer.RegistrationDate), cancellationToken);
return _mapper.Map<CustomerDto>(customer);
}
}