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.

72 lines
2.8 KiB

2 months ago
using MediatR;
using Microsoft.Extensions.Logging;
using CellularManagement.Domain.Common;
using CellularManagement.Domain.Entities;
using CellularManagement.Domain.Repositories;
namespace CellularManagement.Application.Features.Devices.Commands.CreateDevice;
/// <summary>
/// 创建设备命令处理器
/// </summary>
public class CreateDeviceCommandHandler : IRequestHandler<CreateDeviceCommand, OperationResult<Device>>
{
private readonly IDeviceRepository _deviceRepository;
private readonly ILogger<CreateDeviceCommandHandler> _logger;
/// <summary>
/// 初始化命令处理器
/// </summary>
public CreateDeviceCommandHandler(
IDeviceRepository deviceRepository,
ILogger<CreateDeviceCommandHandler> logger)
{
_deviceRepository = deviceRepository;
_logger = logger;
}
/// <summary>
/// 处理创建设备命令
/// </summary>
public async Task<OperationResult<Device>> Handle(CreateDeviceCommand request, CancellationToken cancellationToken)
{
try
{
_logger.LogInformation("Creating new device with serial number: {SerialNumber}", request.SerialNumber);
// 检查序列号是否已存在
if (await _deviceRepository.ExistsBySerialNumberAsync(request.SerialNumber, cancellationToken: cancellationToken))
{
_logger.LogWarning("Device with serial number {SerialNumber} already exists", request.SerialNumber);
return OperationResult<Device>.CreateFailure($"设备序列号 {request.SerialNumber} 已存在");
}
// 创建设备实体
var device = new Device
{
DeviceID = Guid.NewGuid().ToString(),
DeviceName = request.DeviceName,
ProtocolVersion = request.ProtocolVersion,
SupportBands = request.SupportBands,
HardwareVersion = request.HardwareVersion,
SerialNumber = request.SerialNumber,
Comment = request.Comment,
IPAddress = request.IPAddress,
IsDisabled = false,
CreatedAt = DateTime.UtcNow,
UpdatedAt = DateTime.UtcNow
};
// 保存设备
await _deviceRepository.CreateAsync(device, cancellationToken);
_logger.LogInformation("Successfully created device with ID: {DeviceId}", device.DeviceID);
return OperationResult<Device>.CreateSuccess("设备创建成功", device);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error creating device with serial number: {SerialNumber}", request.SerialNumber);
return OperationResult<Device>.CreateFailure($"创建设备时发生错误: {ex.Message}");
}
}
}