目前我在使用干净的架构和 cqrs 模式实现业务逻辑时遇到了麻烦。我正在使用 Mediatr 和 AutoMapper 来做到这一点。我的 cqrs 模式结构如下
以及以下课程:
智能手机Dto.cs
public class SmartphoneDto
{
public int Id { get; set; }
public string serialnumber { get; set; }
}
域实体Smartphone.cs
public class Smartphone
{
public int Id { get; set; }
public string imei { get; set; }
public string serialnumber { get; set; }
public string calculatedValue { get; set; }
}
添加智能手机命令.cs
public class AddSmartphoneCommand : IRequest<bool>
{
public SmartphoneDto SmartphoneDto { get; set; }
}
添加SmartphoneCommandHandler.cs
public class AddSmartphoneCommandHandler : IRequestHandler<AddSmartphoneCommand, bool>
{
private readonly ISmartphoneRepository _smartphoneRepository;
private readonly IMapper _mapper;
public AddSmartphoneCommandHandler(ISmartphoneRepository smartphoneRepository, IMapper mapper)
{
_smartphoneRepository = smartphoneRepository;
_mapper = mapper;
}
public async Task<bool> Handle(AddSmartphoneCommand request, CancellationToken cancellationToken)
{
var smartphone = _mapper.Map<Smartphone>(request.SmartphoneDto);
//Business Logic???
await _smartphoneRepository.AddAsync(smartphone);
return true;
}
}
而且我不确定业务逻辑在哪里,我读过不同的帖子,其中包含类似的建议,但没有可能的解决方案或明确的示例:
第 1 篇文章 据我了解,我们可以将业务逻辑放入外部类中,该外部类作为从命令处理程序的 handle 方法调用的服务
第 2 篇文章 但在这篇文章中表明命令处理程序不必包含任何逻辑。
由于我的困惑,我认为将业务逻辑如下:
{
private readonly ISmartphoneRepository _smartphoneRepository;
private readonly IMapper _mapper;
public AddSmartphoneCommandHandler(ISmartphoneRepository smartphoneRepository, IMapper mapper)
{
_smartphoneRepository = smartphoneRepository;
_mapper = mapper;
}
public async Task<bool> Handle(AddSmartphoneCommand request, CancellationToken cancellationToken)
{
var smartphone = _mapper.Map<Smartphone>(request.SmartphoneDto);
#region businesslogic
//All the business logic in this place
smartphone.imei = someApi.GetAsync("someurl", smartphone.serialnumber);
smartphone.calculatedValue = (smartphone.serialnumber - smartphone.imei) * 0.05;
//end business logic
#endregion
await _smartphoneRepository.AddAsync(smartphone);
return true;
}
}
在结构中放置这种业务逻辑的正确位置是什么?
命令和查询应位于应用层下:
各层之间的依赖关系: