Introduce ICurrentUserService and its implementation to access the current user's username. Inject this service into CreateCatalogHandler and UpdateCatalogHandler to set AddedWho and ChangedWho fields dynamically. Register the service and IHttpContextAccessor in DI, and enable authentication middleware. Update project and using statements accordingly.
41 lines
1.4 KiB
C#
41 lines
1.4 KiB
C#
using AutoMapper;
|
|
using DbFirst.Application.Abstractions;
|
|
using DbFirst.Application.Repositories;
|
|
using DbFirst.Contracts.Catalogs;
|
|
using DbFirst.Domain.Entities;
|
|
using MediatR;
|
|
|
|
namespace DbFirst.Application.Catalogs.Commands;
|
|
|
|
public class CreateCatalogHandler : IRequestHandler<CreateCatalogCommand, CatalogReadDto?>
|
|
{
|
|
private readonly ICatalogRepository _repository;
|
|
private readonly IMapper _mapper;
|
|
private readonly ICurrentUserService _currentUserService;
|
|
|
|
public CreateCatalogHandler(ICatalogRepository repository, IMapper mapper, ICurrentUserService currentUserService)
|
|
{
|
|
_repository = repository;
|
|
_mapper = mapper;
|
|
_currentUserService = currentUserService;
|
|
}
|
|
|
|
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 = _currentUserService.UserName;
|
|
entity.AddedWhen = DateTime.UtcNow;
|
|
entity.ChangedWho = _currentUserService.UserName;
|
|
entity.ChangedWhen = DateTime.UtcNow;
|
|
|
|
var created = await _repository.InsertAsync(entity, cancellationToken);
|
|
return _mapper.Map<CatalogReadDto>(created);
|
|
}
|
|
}
|