Controller or application service making HTTP Requests

  softwareengineering

I’m in the school of thought of ‘thin controllers’, and love to push logic down into services and the domain models. However, I’m wondering if my controller should be making an HTTP Request to another web service or if the application service should do it. It seems that with my school of thinking then “yes” I should push it into the application service. However, this means the application service is stuck with HTTP only. So if I want to use a different communication protocol I’ll need to implement another service like RabbitMQService instead of HttpService.

For example:

public Controller {
    // POST api/controller 
    [HttpPost]
    public async Task PostAsync([FromBody] Dictionary<string, int> data)
    {
        // get data from input json
        var output = service.doWork();
        // prep output data for outgoing HTTP Request

        // this here or in a service like 'HttpService'?
        await _sender.PostAsync(host + "/api/xxxxx", data);
    }
}

Or have the application service send the PostAsync request?

8

Hmm your Controller doesn’t seem very ‘thin’ to me. I would have

public Controller {

    private IElectionService service; //possibly sends over http or Rabbit or whatever

    // POST api/controller 
    [HttpPost]
    public async Task Vote(string electionId, string candidateId)
    {
        await service.Vote(electionId, candidateId);
    }
}

We can imagine that the ElectionService has various injected services

public class ElectionService : IElectionService
{
    private IElectionRepository repo; //calls election api
    public async Task Vote(string electionId, string candidateId)
    {
        var election = repo.GetElection(electionId);
        if(election.Candidates.Includes(candidateId))
        {
            repo.AddVote(new Vote(electionId, candidateId));
        }
        else
        {
            throw an exception!
        }
    }
}


public ElectionRepository_Http : IElectionRepository  {...}
public ElectionRepository_RabbitMQ : IElectionRepository  {...}

etc

5

LEAVE A COMMENT