Is it better to use Automapper in controller or repository pattern?
An easy way to think about it, is in transformations of your models.
- The repository transforms database entities into business models.
- The controller transforms business model into view models.
- The view transforms view models into html.
In this case you are mapping to view models. This is the reponsibility of the controller. Therefore a logical choice would be to do the mapping in the controller code.
Another way to think about it. Another user of the repository could consume the same models but do something different with it. E.g. convert it to a JSON object for use in a REST api. In that case a different mapping is needed. This mapping does not belong in the repository but in the users of the repository.
According to Mosh Hamedani
Mapping is not the responsibility of the repository. It’s the responsibility of your controllers. Your repositories should return domain objects and the client of the repository can decide if it needs to do the mapping. By mapping the domain objects to view models (or something else) inside a repository, you prevent the client of your repositories from getting access to the underlying domain object
So, for an API controller, it makes more sense to have the mapper in the controller