Unit of work pattern is the concept to provide single transaction of multiple works(like insert, update, delete and so on.. ) of an entity as well as of multiple entities which has to be done into database in single go. If any one of the activities get failed then non of the activities will get executed in database, in short entire transaction will be roll backed.
Unit of Work design pattern does two important things: first it maintains in-memory updates and second it sends these in-memory updates as one transaction to the database.
So to achieve the above goals it goes through two steps:
- It maintains lists of business objects in-memory which have been changed (inserted, updated, or deleted) during a transaction.
- Once the transaction is completed, all these updates are sent as one big unit of work to be persisted physically in a database in one go.
See the below flow of transaction without unit of work and with unit of work
How to implement unit of work pattern in C#The way to implement this pattern is as :
- Define an interface for repository to declare database operation.[Note: I will recommend a generic interface ]
- Create a class and implement repository interface.
- Create a class for unit of work.
- Access and implement unit of work in business logic
create a interface to define database operations.
Step 2: Create Repository class
Implement operations defined in above IRepository interface. And create constructor to accept dbContext as parameter.
Step 3: Create Unit of Work class
Unit of work class has the responsibility to provide instance of dbContext to repository(shown as below).
Unit of work class has the three activities
- Create instance of dbContext
- Create instance of repositories against this single instance of dbContext
- Save the changes of dbContext into database(changes could be of one or more repositories)
Step 4: Access and implement unit of work in business logic
In below order class, instance of unit of work class is created to handle all type of communication with database. Here in AddOrder method two instances are created on for order and second for customer details. And both entity is saved into database as a single work unit.
No comments:
Post a Comment