如何在 MediatoR 模式中传递对象类型数组?

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

希望你一切都好!

我正在使用 MediatoR 设计模式,其中我想接受集合数组作为控制器中的对象。早些时候我用作单个对象,但现在我如何允许 MediatoR 接受数组作为参数。

来自:

public async Task<ActionResult<ServiceResponse<int>>>
  AddField(**AddFieldCommand** objFieldCommand)

致:

public async Task<ActionResult<ServiceResponse<int>>> 
 AddField(**AddFieldCommand[]** objFieldCommand)

我尝试这样做,但它给了我以下错误:

Severity    Code    Description Project File    Line    Suppression State
Error   CS0311  The type 'Application.Commands.Fields.AddFieldCommand[]' cannot be used as type parameter 'TRequest' in the generic type or method 'IRequestHandler<TRequest, TResponse>'. There is no implicit reference conversion from 'Application.Commands.Fields.AddFieldCommand[]' to 'MediatR.IRequest<Application.Common.ServiceResponse<int>>'.   Application C:\Users\Admin\Documents\Projects\Source Code\Application\Commands\Fields\AddFieldCommand.cs    28  Active


   public class AddFieldCommandHandler : IRequestHandler<AddFieldCommandAggregate, ServiceResponse<int>>
{
    private readonly IFieldsService _fieldService;

    public AddFieldCommandHandler(IFieldsService fieldService)
    {
        _fieldService = fieldService;
    }

    public async Task<ServiceResponse<int>> Handle(AddFieldCommandAggregate request, CancellationToken cancellationToken)
    {
        return await _fieldService.AddField(request: request, cancellationToken: cancellationToken);
    }
}

错误出现在公共类 AddFieldCommandHandler 中,该行被标记为粗体。 有人可以帮帮我吗?

c# asp.net-core design-patterns mediator
1个回答
1
投票

根据您的设置,我怀疑您有一些处理程序接受

AddFieldCommand
并用它调用一些方法。现在您很可能想执行一个循环来处理所有项目。

所以我怀疑你大致有类似这样的代码:

public async Task Handle(AddFieldCommand data)
{
    // here you have all the logic
    PerformAction(data);
}

所以现在需要将其重构为:

public async Task Handle(AddFieldCommandAggregate multiData)
{
    foreach(var data in mulitData.Data)
    {
        // here you have all the logic
        PerformAction(data);
    }
}

并且您需要定义聚合类:

public class AddFieldCommandAggregate
{
    public AddFieldCommand[] Data { get; set; }
}
© www.soinside.com 2019 - 2024. All rights reserved.