Introduction of Repository and UnitOfWork, unitofwork
What is Repository? Uncle Martin's book also explains that it is a link between the data ing layer and the domain. It serves as a domain object ing set in the memory, it separates the segments of domain objects and database access code. The Repository is driven by the DomainObject, And the Repository is used to implement services not related to the DomainObject but restricted by the DomainObject. For example, the CRUD operation is not a concern of the domain model, but the domain model must be mapped to the Data Relationship and saved to the database. A domain model must have the corresponding Repository to process the connection process with the data layer. However, not all domainobjects have the same Repository constraints. Maybe this domain object does not correspond to the Repository deletion operation, but other objects do, therefore, generic Repository <T> is not suitable. However, for the sake of concise code reuse, we still use the concise IRepository <T> interface according to the actual situation, just as we sometimes Use POCO as DTO or VO for simplicity. If Repository is not introduced, I don't think it is necessary to implement the DAL layer, because DbContext itself is the DAL layer, and then it is necessary to define the IDAL interface for DbContext to avoid coupling with the BLL layer. Here we can see the difference between Repository and DAL. One is driven by the domain service, and the other is caused by decoupling.
UnitOfWork unit, in order to reduce the business layer's frequent calls to the SaveChanges of DbContext to synchronize database operations (update and submit multiple objects once to reduce the interaction process with the database), DbContext must be closed to the business layer, therefore, we need to add an interface that is open to the business layer. If you place the SaveChanges method in each Repository or DAL, the business layer will frequently write data to the database when coordinating multiple Repository transaction operations. After all the SaveChanges in the Repository are separated (or the operations such as Undo and destroy after the unit work is completed), The SaveChanges are called in a unified manner at the business layer through interfaces, which greatly improves the efficiency, it also represents a complete unit work business.