Why and in which cases use each?
I believe using Dbcontext directly, you end up being tied/tied to the technology, being a disadvantage if you need to change in the future.
Another disadvantage to use Dbcontext directly in the service is that its service involves business rules, already Dbcontext is related to a technology. So, if you change the technology, you will need to touch the code where are your business rules, this is not cool.
In the second example why not use a generic repository? is no longer practical?
Repository isolates domain objects (business-related) from access code details and mapping those objects with the database. That is, it adds a layer of separation between the layers of data access and domain access.
In the case of the project that you are developing, you would have to create another project in your solution to implement this Pattern design. I believe it is more practical and recommended to use this standard.
It is bad practice for one service to instantiate another and make use of that?
Not, each service has its own responsibility and in many cases one service may need another service.
Example: In a scenario where a Customer withdraws into their account, let’s assume that the Customer has a service called Clienteservice.
public class ClienteServico
{
//...
public void RealizarSaque()
{
//Nesse ponto pode ser que o cliente não tenha saldo para saque
//e você precisa de um serviço de um objeto ContaCorrenteServiço
//por exemplo para retornar/verificar o saldo antes do saque
}
//...
}
Following this reasoning, I would also recommend you to work with dependency injection and inversion of control of repositories/services, according to the answer of Thiago Custodio (but not only in controllers, but also in their services that will depend on repository queries, etc.).
But the controller shouldn’t just call the services?
– Apolo
Yes, the difference is that you will not instantiate the services in the controllers, but rather receive them as a dependency.
– Thiago Custodio
thanks for the reply but doing a research and several professionals in the field do not recommend the use for several reasons.
– Apolo
@mustache what you think of it?
– Apolo
@Gypsy Morrison Mendez what you think of this?
– Apolo
I find it unnecessary to start developing an application without properly understanding the responsibilities of a repository. For the vast majority of applications, a repository is completely unnecessary, increases layer-to-layer complexity and can still impact performance. Only justifies injecting dependencies if the team of programmers opts for automated testing, as @Thiagocustodio stated in its reply.
– Leonel Sanches da Silva
@Apollo, bigown and gypsy were not notified by their comments, see how notifications actually work. Regardless, here you don’t usually "run after" a certain user to ask for opinions or clarification (except in [chat]).
– bfavaretto