I've been looking for some implementations of Service Layer and Controller interaction in blogs and in some open source projects. All of them seem to refer DbContext object in repository classes but avoided to use in service classes. Service classes essentially using a IQueryable<T> references of DbSet<T>. I want to know why this practice is good and why DbContext shouldn't have a reference in Service Layer.
Why DbContext object shouldn't be referred in Service Layer?
c#;entity framework
NOTE: I'm writing this answer as it would apply to a Programmers.SE question.A big part of application design is abstraction i.e. hiding away lower-level details and providing a simple conceptual interface to consumers. A related principle is encapsulation - the internal details of an operation should remain within the component and should not leak into the outside world.Typically, we would like to have all DB-related code in a single location. So we create a dedicated layer for it and encapsulate all DB logic in that layer. As far as the service layer is concerned, it does not know anything about how the data is retrieved. It just asks for some data from the data layer, magically gets it, and runs business logic on it.This makes it very easy to change the DB logic. For example, swapping the underlying database with an equivalent one has negligible impact on other areas of the application. Because the service knows nothing about the DB, as long as it gets the same data back, it will continue working exactly as before.Note that this also applies to other layers. The UI layer knows nothing of business logic. It talks in terms of domain-level abstractions and shows them to the consumer. How those domain objects are generated and manipulated is the job of the business layer and hidden within it.