You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

55 lines
1.9 KiB

using MediatR;
using Microsoft.Extensions.Logging;
using CellularManagement.Domain.Common;
using CellularManagement.Domain.Repositories;
namespace CellularManagement.Application.Features.Devices.Commands.DeleteDevice;
/// <summary>
/// 删除设备命令处理器
/// </summary>
public class DeleteDeviceCommandHandler : IRequestHandler<DeleteDeviceCommand, OperationResult<bool>>
{
private readonly IDeviceRepository _deviceRepository;
private readonly ILogger<DeleteDeviceCommandHandler> _logger;
/// <summary>
/// 初始化删除设备命令处理器
/// </summary>
public DeleteDeviceCommandHandler(
IDeviceRepository deviceRepository,
ILogger<DeleteDeviceCommandHandler> logger)
{
_deviceRepository = deviceRepository;
_logger = logger;
}
/// <summary>
/// 处理删除设备命令
/// </summary>
public async Task<OperationResult<bool>> Handle(DeleteDeviceCommand request, CancellationToken cancellationToken)
{
try
{
_logger.LogInformation("开始处理删除设备命令,设备ID: {DeviceId}", request.DeviceId);
var result = await _deviceRepository.DeleteByIdAsync(request.DeviceId, cancellationToken);
if (result)
{
_logger.LogInformation("设备删除成功,设备ID: {DeviceId}", request.DeviceId);
return OperationResult<bool>.CreateSuccess(true);
}
else
{
_logger.LogWarning("设备删除失败,设备ID: {DeviceId}", request.DeviceId);
return OperationResult<bool>.CreateFailure("设备删除失败");
}
}
catch (Exception ex)
{
_logger.LogError(ex, "删除设备时发生错误,设备ID: {DeviceId}", request.DeviceId);
return OperationResult<bool>.CreateFailure($"删除设备时发生错误: {ex.Message}");
}
}
}