ABP Unit of Work (工作单元)

Unit of Work in ABP is used to manage database connections and transactions.

Database connections need to be opened as late as possible and released as early as possible. Performing database operations in a transactional manner has been considered a best practice.

Connection and Transaction Management in ABP#

ABP combines these two methods and provides a simple yet effective model.

Repository Class#

The repository is the main class for performing database operations. When entering a repository method, ABP will open a database connection (may not be immediate, but will definitely be opened the first time the database is used, depending on the ORM provider's implementation) and start a transaction. Therefore, a connection can be safely used within a repository method. After the method ends, the transaction is committed and the connection is released. If the repository method throws any exceptions, the transaction is rolled back and the connection is released. This way, the repository method acts as an atomic unit of work.

If a repository method calls other repository methods (generally, if a unit of work calls other unit of work methods), they share the same connection and transaction. The first method to enter manages the connection and transaction, and other methods use the same connection and transaction.

Unit of Work#

The unit of work is implicitly effective for repositories and application service methods. If you want to control database connections and transactions elsewhere, you can explicitly use it.


Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.