Refactor Catalogs to use MediatR and CQRS pattern
Replaced direct service usage in CatalogsController with MediatR-based commands and queries for all CRUD operations. Added command/query and handler classes for Catalog operations. Updated dependency injection to register MediatR and removed ICatalogService. Improved code maintainability and testability by adopting CQRS architecture.
This commit is contained in:
@@ -0,0 +1,23 @@
|
||||
using AutoMapper;
|
||||
using DbFirst.Domain.Repositories;
|
||||
using MediatR;
|
||||
|
||||
namespace DbFirst.Application.Catalogs.Queries;
|
||||
|
||||
public class GetAllCatalogsHandler : IRequestHandler<GetAllCatalogsQuery, List<CatalogReadDto>>
|
||||
{
|
||||
private readonly ICatalogRepository _repository;
|
||||
private readonly IMapper _mapper;
|
||||
|
||||
public GetAllCatalogsHandler(ICatalogRepository repository, IMapper mapper)
|
||||
{
|
||||
_repository = repository;
|
||||
_mapper = mapper;
|
||||
}
|
||||
|
||||
public async Task<List<CatalogReadDto>> Handle(GetAllCatalogsQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var items = await _repository.GetAllAsync(cancellationToken);
|
||||
return _mapper.Map<List<CatalogReadDto>>(items);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
using DbFirst.Application.Catalogs;
|
||||
using MediatR;
|
||||
|
||||
namespace DbFirst.Application.Catalogs.Queries;
|
||||
|
||||
public record GetAllCatalogsQuery : IRequest<List<CatalogReadDto>>;
|
||||
@@ -0,0 +1,23 @@
|
||||
using AutoMapper;
|
||||
using DbFirst.Domain.Repositories;
|
||||
using MediatR;
|
||||
|
||||
namespace DbFirst.Application.Catalogs.Queries;
|
||||
|
||||
public class GetCatalogByIdHandler : IRequestHandler<GetCatalogByIdQuery, CatalogReadDto?>
|
||||
{
|
||||
private readonly ICatalogRepository _repository;
|
||||
private readonly IMapper _mapper;
|
||||
|
||||
public GetCatalogByIdHandler(ICatalogRepository repository, IMapper mapper)
|
||||
{
|
||||
_repository = repository;
|
||||
_mapper = mapper;
|
||||
}
|
||||
|
||||
public async Task<CatalogReadDto?> Handle(GetCatalogByIdQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var item = await _repository.GetByIdAsync(request.Id, cancellationToken);
|
||||
return item == null ? null : _mapper.Map<CatalogReadDto>(item);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
using DbFirst.Application.Catalogs;
|
||||
using MediatR;
|
||||
|
||||
namespace DbFirst.Application.Catalogs.Queries;
|
||||
|
||||
public record GetCatalogByIdQuery(int Id) : IRequest<CatalogReadDto?>;
|
||||
Reference in New Issue
Block a user