在 .Net Clean Architecture 应用程序中使用 Mediatr 实现 CQRS 模式时,我应该将业务逻辑放在哪里?

问题描述 投票:0回答:1

目前我在使用干净的架构和 cqrs 模式实现业务逻辑时遇到了麻烦。我正在使用 Mediatr 和 AutoMapper 来做到这一点。我的 cqrs 模式结构如下

  • 应用核心
    • DTO
      • 智能手机Dto.cs
    • 特点
      • 智能手机
        • 处理程序
          • 命令
            • 添加SmartphoneCommandHandler.cs
          • 查询
        • 请求
          • 命令
            • 添加智能手机命令.cs
          • 查询
  • 域核心
    • 智能手机.cs

以及以下课程:

智能手机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;
    }
}

在结构中放置这种业务逻辑的正确位置是什么?

asp.net .net cqrs clean-architecture
1个回答
0
投票

命令和查询应位于应用层下:

各层之间的依赖关系:

  • 领域层: 不依赖于任何层。 包含:实体、聚合、值对象、存储库合约。
  • 应用层: 取决于域和基础设施层。 包含:CQRS、用例、API 合约和实现。
  • 基础设施层: 取决于域层。 包含:存储库实现、ORM(例如实体框架)、密码学、日志记录等。
  • 表示层: 取决于应用层。
© www.soinside.com 2019 - 2024. All rights reserved.