Rahul Parab
Rahul Parab

Reputation: 87

How to pass array of objects type in MediatoR patterns?

Hope You are doing well!

I am using MediatoR design pattern in which i want to accept array of collections as an object in my controller. Earlier i was using as a single object but now how can i allow the MediatoR to accept array as parameter.

From:

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

To:

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

I tried doing this but it is giving me the below error:

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);
    }
}

error comes in line public class AddFieldCommandHandler which is marked as bold. Can any one please help me?

Upvotes: 1

Views: 674

Answers (1)

Michał Turczyn
Michał Turczyn

Reputation: 37460

By your setup i suspect you have some handler that accepts AddFieldCommand and invokes some method with it. Now you want to perform most probably a loop to handle all items.

So i suspect you roughly have code similar to this:

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

so now this would be needed to be refactored to:

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

and you would need to define aggregate class:

public class AddFieldCommandAggregate
{
    public AddFieldCommand[] Data { get; set; }
}

Upvotes: 1

Related Questions