Reputation: 364
Just to learn about patterns I'm creating my Web API with these projects: Entities, Repositories, Service and the API application.
Each controller in APIs use dependency injection to his corresponding service; each service use DI to multiple repositories; Repositories are used to get data from the DbContext and Entities contains DbContext and the DbSets.
As example let's say that when I call the /teams/1 endpoint:
GetTeam(id)
function in controller call _teamService.GetTeam(id);
_teamRepository.GetTeam(id);
Context.Team.First(...)
a give back to the service the Team entity model;Is this a right way to manage the flow?
In addition, imagine that the controller must retrieve the team and all its competitions: is it right to inject the CompetitionRepository and use it from the TeamService? Something like:
TeamService.cs
return new DTOObject {
team = _teamRepo.GetTeam(id),
competitions = _compRepo.GetCompsByTeam(id) <-- is a list
}
Upvotes: 1
Views: 3703
Reputation: 23551
I prefer to return entities from my services and not DTOs. The reason is that sometimes the result of a service call is used to create an ASP.NET MVC View Model and sometimes a DTO to return as a JSON. Sometimes the requirements for these DTOs are different, the server side ViewModels can see things that should not be exposed to the client. You can make a DTO in your service layer but in most cases it is just another mapping that you have to take care of for not that much value. This is why I create DTOs or ViewModels directly from entities in the controller.
Also the repository pattern is mostly useless. It might be useful if you change your data store but in practice these kinds of changes come with a lot of other changes to the business logic so most of your service layer is rewritten anyway so the value is lost.
Upvotes: 5