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:
OlgunR
2026-01-19 09:00:06 +01:00
parent c8c75b1dc5
commit 870b10779e
15 changed files with 185 additions and 11 deletions

View File

@@ -1,4 +1,7 @@
using DbFirst.Application.Catalogs; using DbFirst.Application.Catalogs;
using DbFirst.Application.Catalogs.Commands;
using DbFirst.Application.Catalogs.Queries;
using MediatR;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
namespace DbFirst.API.Controllers; namespace DbFirst.API.Controllers;
@@ -7,24 +10,24 @@ namespace DbFirst.API.Controllers;
[Route("api/[controller]")] [Route("api/[controller]")]
public class CatalogsController : ControllerBase public class CatalogsController : ControllerBase
{ {
private readonly ICatalogService _service; private readonly IMediator _mediator;
public CatalogsController(ICatalogService service) public CatalogsController(IMediator mediator)
{ {
_service = service; _mediator = mediator;
} }
[HttpGet] [HttpGet]
public async Task<ActionResult<IEnumerable<CatalogReadDto>>> GetAll(CancellationToken cancellationToken) public async Task<ActionResult<IEnumerable<CatalogReadDto>>> GetAll(CancellationToken cancellationToken)
{ {
var result = await _service.GetAllAsync(cancellationToken); var result = await _mediator.Send(new GetAllCatalogsQuery(), cancellationToken);
return Ok(result); return Ok(result);
} }
[HttpGet("{id:int}")] [HttpGet("{id:int}")]
public async Task<ActionResult<CatalogReadDto>> GetById(int id, CancellationToken cancellationToken) public async Task<ActionResult<CatalogReadDto>> GetById(int id, CancellationToken cancellationToken)
{ {
var result = await _service.GetByIdAsync(id, cancellationToken); var result = await _mediator.Send(new GetCatalogByIdQuery(id), cancellationToken);
if (result == null) if (result == null)
{ {
return NotFound(); return NotFound();
@@ -35,7 +38,7 @@ public class CatalogsController : ControllerBase
[HttpPost] [HttpPost]
public async Task<ActionResult<CatalogReadDto>> Create(CatalogWriteDto dto, CancellationToken cancellationToken) public async Task<ActionResult<CatalogReadDto>> Create(CatalogWriteDto dto, CancellationToken cancellationToken)
{ {
var created = await _service.CreateAsync(dto, cancellationToken); var created = await _mediator.Send(new CreateCatalogCommand(dto), cancellationToken);
if (created == null) if (created == null)
{ {
return Conflict(); return Conflict();
@@ -46,7 +49,7 @@ public class CatalogsController : ControllerBase
[HttpPut("{id:int}")] [HttpPut("{id:int}")]
public async Task<ActionResult<CatalogReadDto>> Update(int id, CatalogWriteDto dto, CancellationToken cancellationToken) public async Task<ActionResult<CatalogReadDto>> Update(int id, CatalogWriteDto dto, CancellationToken cancellationToken)
{ {
var current = await _service.GetByIdAsync(id, cancellationToken); var current = await _mediator.Send(new GetCatalogByIdQuery(id), cancellationToken);
if (current == null) if (current == null)
{ {
return NotFound(); return NotFound();
@@ -56,7 +59,7 @@ public class CatalogsController : ControllerBase
return BadRequest("CatTitle cannot be changed."); return BadRequest("CatTitle cannot be changed.");
} }
var updated = await _service.UpdateAsync(id, dto, cancellationToken); var updated = await _mediator.Send(new UpdateCatalogCommand(id, dto), cancellationToken);
if (updated == null) if (updated == null)
{ {
return NotFound(); return NotFound();
@@ -67,7 +70,7 @@ public class CatalogsController : ControllerBase
[HttpDelete("{id:int}")] [HttpDelete("{id:int}")]
public async Task<IActionResult> Delete(int id, CancellationToken cancellationToken) public async Task<IActionResult> Delete(int id, CancellationToken cancellationToken)
{ {
var deleted = await _service.DeleteAsync(id, cancellationToken); var deleted = await _mediator.Send(new DeleteCatalogCommand(id), cancellationToken);
if (!deleted) if (!deleted)
{ {
return NotFound(); return NotFound();

View File

@@ -16,6 +16,7 @@
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference> </PackageReference>
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" /> <PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" />
<PackageReference Include="MediatR.Extensions.Microsoft.DependencyInjection" Version="11.1.0" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

@@ -3,7 +3,7 @@ using DbFirst.Application.Catalogs;
using DbFirst.Domain.Repositories; using DbFirst.Domain.Repositories;
using DbFirst.Infrastructure; using DbFirst.Infrastructure;
using DbFirst.Infrastructure.Repositories; using DbFirst.Infrastructure.Repositories;
using Microsoft.EntityFrameworkCore; using MediatR;
using DbFirst.API.Middleware; using DbFirst.API.Middleware;
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
@@ -38,7 +38,6 @@ builder.Services.AddInfrastructure(builder.Configuration);
builder.Services.AddApplication(); builder.Services.AddApplication();
builder.Services.AddScoped<ICatalogRepository, CatalogRepository>(); builder.Services.AddScoped<ICatalogRepository, CatalogRepository>();
builder.Services.AddScoped<ICatalogService, CatalogService>();
var app = builder.Build(); var app = builder.Build();

View File

@@ -0,0 +1,6 @@
using DbFirst.Application.Catalogs;
using MediatR;
namespace DbFirst.Application.Catalogs.Commands;
public record CreateCatalogCommand(CatalogWriteDto Dto) : IRequest<CatalogReadDto?>;

View File

@@ -0,0 +1,36 @@
using AutoMapper;
using DbFirst.Domain.Entities;
using DbFirst.Domain.Repositories;
using MediatR;
namespace DbFirst.Application.Catalogs.Commands;
public class CreateCatalogHandler : IRequestHandler<CreateCatalogCommand, CatalogReadDto?>
{
private readonly ICatalogRepository _repository;
private readonly IMapper _mapper;
public CreateCatalogHandler(ICatalogRepository repository, IMapper mapper)
{
_repository = repository;
_mapper = mapper;
}
public async Task<CatalogReadDto?> Handle(CreateCatalogCommand request, CancellationToken cancellationToken)
{
var existing = await _repository.GetByTitleAsync(request.Dto.CatTitle, cancellationToken);
if (existing != null)
{
return null;
}
var entity = _mapper.Map<VwmyCatalog>(request.Dto);
entity.AddedWho = "system";
entity.AddedWhen = DateTime.UtcNow;
entity.ChangedWho = "system";
entity.ChangedWhen = DateTime.UtcNow;
var created = await _repository.InsertAsync(entity, cancellationToken);
return _mapper.Map<CatalogReadDto>(created);
}
}

View File

@@ -0,0 +1,5 @@
using MediatR;
namespace DbFirst.Application.Catalogs.Commands;
public record DeleteCatalogCommand(int Id) : IRequest<bool>;

View File

@@ -0,0 +1,19 @@
using DbFirst.Domain.Repositories;
using MediatR;
namespace DbFirst.Application.Catalogs.Commands;
public class DeleteCatalogHandler : IRequestHandler<DeleteCatalogCommand, bool>
{
private readonly ICatalogRepository _repository;
public DeleteCatalogHandler(ICatalogRepository repository)
{
_repository = repository;
}
public async Task<bool> Handle(DeleteCatalogCommand request, CancellationToken cancellationToken)
{
return await _repository.DeleteAsync(request.Id, cancellationToken);
}
}

View File

@@ -0,0 +1,6 @@
using DbFirst.Application.Catalogs;
using MediatR;
namespace DbFirst.Application.Catalogs.Commands;
public record UpdateCatalogCommand(int Id, CatalogWriteDto Dto) : IRequest<CatalogReadDto?>;

View File

@@ -0,0 +1,38 @@
using AutoMapper;
using DbFirst.Domain.Entities;
using DbFirst.Domain.Repositories;
using MediatR;
namespace DbFirst.Application.Catalogs.Commands;
public class UpdateCatalogHandler : IRequestHandler<UpdateCatalogCommand, CatalogReadDto?>
{
private readonly ICatalogRepository _repository;
private readonly IMapper _mapper;
public UpdateCatalogHandler(ICatalogRepository repository, IMapper mapper)
{
_repository = repository;
_mapper = mapper;
}
public async Task<CatalogReadDto?> Handle(UpdateCatalogCommand request, CancellationToken cancellationToken)
{
var existing = await _repository.GetByIdAsync(request.Id, cancellationToken);
if (existing == null)
{
return null;
}
var entity = _mapper.Map<VwmyCatalog>(request.Dto);
entity.Guid = request.Id;
entity.CatTitle = existing.CatTitle;
entity.AddedWho = existing.AddedWho;
entity.AddedWhen = existing.AddedWhen;
entity.ChangedWho = "system";
entity.ChangedWhen = DateTime.UtcNow;
var updated = await _repository.UpdateAsync(request.Id, entity, cancellationToken);
return updated == null ? null : _mapper.Map<CatalogReadDto>(updated);
}
}

View File

@@ -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);
}
}

View File

@@ -0,0 +1,6 @@
using DbFirst.Application.Catalogs;
using MediatR;
namespace DbFirst.Application.Catalogs.Queries;
public record GetAllCatalogsQuery : IRequest<List<CatalogReadDto>>;

View File

@@ -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);
}
}

View File

@@ -0,0 +1,6 @@
using DbFirst.Application.Catalogs;
using MediatR;
namespace DbFirst.Application.Catalogs.Queries;
public record GetCatalogByIdQuery(int Id) : IRequest<CatalogReadDto?>;

View File

@@ -10,6 +10,7 @@
<PackageReference Include="AutoMapper" Version="12.0.1" /> <PackageReference Include="AutoMapper" Version="12.0.1" />
<PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="12.0.1" /> <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="12.0.1" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.2" /> <PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.2" />
<PackageReference Include="MediatR.Extensions.Microsoft.DependencyInjection" Version="11.1.0" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

@@ -1,4 +1,5 @@
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using MediatR;
namespace DbFirst.Application; namespace DbFirst.Application;
@@ -7,6 +8,7 @@ public static class DependencyInjection
public static IServiceCollection AddApplication(this IServiceCollection services) public static IServiceCollection AddApplication(this IServiceCollection services)
{ {
services.AddAutoMapper(typeof(DependencyInjection).Assembly); services.AddAutoMapper(typeof(DependencyInjection).Assembly);
services.AddMediatR(typeof(DependencyInjection).Assembly);
return services; return services;
} }
} }