Quantcast
Channel: User Álvaro García - Software Engineering Stack Exchange
Viewing all articles
Browse latest Browse all 40

Why is it so common to use the dbContext directly in the controller in a WebApi application?

$
0
0

Actually, in a Web API application using Entity Core, it seems very common to inject the application context to the controllers, so the controllers use directly the dbContext to do its work.

Something like this:

[HttpGet]public async Task<ActionResult<List<ActorDTO>>> GetAsync(){    return await _contextConsultas.Actores.ToListAsync();}

But I have some disavantages with this solution.

One is that what happen if I want to use a new version of entity core. Sometimes there are some breaking updates that modify the behavior of entity core. Perhaps how it is work an include or any other functionality. In this case, the controller has to know the implementation and the behaviour of entity core, and I should to modify all the endpoints in all the controllers.

If the controller would use a repository, and interface that is implemented by class, the controller doesn't need to know the implementation, so if in the future I want to use another version that implements the interface, I can use it and the controller is not needed to be modify.

The code would be something like that:

[HttpGet]public async Task<ActionResult<List<ActorDTO>>> GetAsync(){    return await _applicationContex.GetAllActorsAsync();}

Later, in the main project, if I am using dependency injection, I only need to chage the implementation that I want to use.

But seeing many examples in which the controller uses the dbContext directly, I am wondering if nowdays it is still as useful as I think to wrap the dbContext in a repository.

Thanks.


Viewing all articles
Browse latest Browse all 40

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>