Home > Net >  What is the name of the architecture and the purpose of using dbcontext in a service rather than a c
What is the name of the architecture and the purpose of using dbcontext in a service rather than a c

Time:04-01

I have multiple API controllers that have GET/POST functions which require database access (read/write). So I have created the dbcontext and injected it into every controller via constructor injection. Then within the GET/POST functions, I am using Entity Framework querying syntax like:

_context.TableName.Where...Select...ToListAsync()

I have been asked to review this and rather than injecting the dbcontext, make a service out of it and inject the service into the controller.

Am I correct to understand that this means the service will have functions (like GetData(), InsertData(val)). Within this service functions will be the entity framework querying that is interacting with the database. I must then inject the service into the controller so that when the functions GET/POST want to interact with the database they make use of the service functions. I believe this is so as to separate the Entity Framework query syntax and place it into service class rather than the controller.

What is such an architecture called?

CodePudding user response:

Its called repository pattern/layered architecture.

CodePudding user response:

It is called Repository pattern, by extracting database logic in service/repository you are making it more readable.

Ideally you api layer should only worry about following points

  1. api endpoints
  2. versioning
  3. general exception handling
  4. authentication and authorization

Database or business logic should be in separate layer, this layer handles all business logic and database access.

If you want to go deeper you could also separate business layer and database layer too, So your api will forward request to Business layer and business layer will perform required business logic, for database access Business logic will call Database layer for data. Main advantage of this approach is that if you want to change database provider you will only need to modify Database layer, this approach is called 3 Layer architecture.

** EDIT **

Here is example web app with .net 5 Api and angular 12 with Sql server

CodePudding user response:

"layered architecture" separate business layer and database layer from presentation also known as n-tier architecture.

Most commonly 3 Layer architecture; https://www.oreilly.com/library/view/software-architecture-patterns/9781491971437/ch01.html

What you call these 3 layers seems to vary a lot!

but in a nutshell

  1. Frontend / UI/ Presentation /Architecture layer*(DDD)
  2. Logic / Service layer / Business layer /Domain layer*(DDD)
  3. Backend/Data layer/Repository layer*/ Infrastructure*(DDD)

the * just means there's more to the story

  • Related