Pregunta

When creating a new .NET Core Web API the controllers will be put in the Controllers directory. I want to create request models for incoming requests (for validation purposes) and response models which might differ from the database models. So a basic folder structure could be

API
├── Controllers
│   ├── UsersController
│   └── TodosController
├── RequestModels
│   ├── Users
│   │   ├── GetUserByIdDto
│   │   └── CreateUserDto
│   └── Todos
│   │   ├── GetTodoByIdDto
│   │   └── CreateTodoDto
└── ResponseModels
    ├── Users
    │   └── UserViewModel
    └── Todos
        └── TodoViewModel

Making DTOs reusable might add more complexity and might be even worse. This has already been asked here

https://stackoverflow.com/questions/44349199/reusing-dto-for-various-request-response-types-vs-explicitness-of-what-is-requir

Wouldn't it make sense to keep the models with the controller and organize by domain? The folder structure would then be

API
├── Users
│   ├── UsersController
│   ├── RequestModels
|   |   ├── GetUserByIdDto
│   |   └── CreateUserDto
│   └── ResponseModels
|       └── UserViewModel
└── Todos
    ├── TodosController
    ├── RequestModels
    |   ├── GetTodoByIdDto
    |   └── CreateTodoDto
    └── ResponseModels
        └── TodoViewModel

So this question might be opinion based but maybe there are some pros / cons for one or another approach.

¿Fue útil?

Solución

I prefer the second approach (sometimes called a feature-based approach). It keeps things you tend to work with in one place. If you want to work with a User, you work with the User controller and models, and they're right there, nicely separated from, say, Clients or Invoices or whatever.

Imagine you have 30 controllers and 10 or 20 request/response models for each controller. Then imagine them organized by your first structure, and how much jumping and searching you'd have to do for a simple task.

Licenciado bajo: CC-BY-SA con atribución
scroll top