Search This Blog

Sunday, June 11, 2017

Design Pattern : What is unit of work pattern?

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 :

  1. Define an interface for repository to declare database operation.[Note: I will recommend a generic interface ]
  2. Create a class and implement repository interface.
  3. Create a class for unit of work.
  4. Access and implement unit of work in business logic
Step 1: Define Interface

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

  1. Create instance of dbContext
  2. Create instance of repositories against this single instance of dbContext
  3. 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.