Home > Enterprise >  Do we need request handlers while we use minimal api endpoints?
Do we need request handlers while we use minimal api endpoints?

Time:12-02

Typically, when we want to have testable application logic, we usually create controller that can looks like this:

[HttpGet]
public IActionResult SomeAction()
{
    var result = _someRequestHandler.Handle();
    return Ok(result);
}

I think we do it because:

  1. Controllers are difficult to test
  2. It's nice to separate logic and controllers
  3. Controllers could has too many dependencies (fat constructor with multiple Dependency Injections)

But when are using NET 7 minimal API's, then our "controllers method" are just static class. So there are easily testable, but I'm not sure about one thing.

Do you think we should still using something like request handlers? Writing all the logic in a "controller action" seems strange to me, what do you think about it given the known good practices?

CodePudding user response:

I would argue that almost all the same concerns can be applied to the Minimal API handlers.

  1. Controllers are difficult to test

I would argue that not that much (see the docs). The main concern is the "implicit" dependencies which can used by controllers (like HttpContext) which are explicit in Minimal API handlers.

  1. It's nice to separate logic and controllers

I would argue that the same can be valid for Minimal API handlers, especially if they rely on special parameters (like aforementioned HttpContext).

  1. Controllers could has too many dependencies (fat constructor with multiple Dependency Injections)

Controllers support resolution of dependencies in actions (like Minimal API endpoints) via FromServicesAttribute (see the docs):

public IActionResult About([FromServices] IDateTime dateTime)
{
    return Content( $"Current server time: {dateTime.Now}");
} 

So if you have specific dependencies that are not "controller-wide" and are valid to only specific actions you can inject them directly into those actions.

So in short - the reasons to introduce the handlers would be almost the same only slightly "relaxed".

  • Related